最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to find sum of duplicate values in an array using javascript - Stack Overflow

programmeradmin1浏览0评论

I have the following array with me. And my aim is to create a new array by removing duplicate values from this array.

var xDataValuesdash =  [    [ 'Anantapur', 10, '#C21466' ],
                            [ 'Anantapur', 20, '#A983D0' ],
                            [ 'Chittoor', 30, '#A993D0' ],
                            [ 'Anantapur', 30, '#544DDF' ],
                            [ 'Anantapur', 4, '#A994D0' ],
                            [ 'Chittoor', 40, '#544BDF' ]  ];

ie, The resultant array must be

var new_xDataValuesdash = [[ 'Anantapur', 64, '#C21466' ], 
                           [ 'Chittoor', 70, '#544BDF' ]];

While removing duplicates its value must be added to the unqiue value.

I have the following array with me. And my aim is to create a new array by removing duplicate values from this array.

var xDataValuesdash =  [    [ 'Anantapur', 10, '#C21466' ],
                            [ 'Anantapur', 20, '#A983D0' ],
                            [ 'Chittoor', 30, '#A993D0' ],
                            [ 'Anantapur', 30, '#544DDF' ],
                            [ 'Anantapur', 4, '#A994D0' ],
                            [ 'Chittoor', 40, '#544BDF' ]  ];

ie, The resultant array must be

var new_xDataValuesdash = [[ 'Anantapur', 64, '#C21466' ], 
                           [ 'Chittoor', 70, '#544BDF' ]];

While removing duplicates its value must be added to the unqiue value.

Share Improve this question asked Oct 15, 2016 at 6:03 Hormis LonaHormis Lona 5232 gold badges8 silver badges19 bronze badges 3
  • Whats the logic for this duplicates,in each array you have 3 ponents one is anatapur,10 and some string, I understand you have to get unique values of first string and add the next values and what about the last one in the array ,what should we consider here – Geeky Commented Oct 15, 2016 at 6:11
  • Why does first array is results have first hex value from original array, though second result has second hex value from original array? – guest271314 Commented Oct 15, 2016 at 6:14
  • third value can be any of the value from the duplicate. That doesnt matter. – Hormis Lona Commented Oct 15, 2016 at 6:17
Add a ment  | 

5 Answers 5

Reset to default 5

Try this

var xDataValuesdash =  [    [ 'Anantapur', 10, '#C21466' ],
    [ 'Anantapur', 20, '#A983D0' ],
    [ 'Chittoor', 30, '#A993D0' ],
    [ 'Anantapur', 30, '#544DDF' ],
    [ 'Anantapur', 4, '#A994D0' ],
    [ 'Chittoor', 40, '#544BDF' ]  ];

var sum = {},result;

for (var i=0,c;c=xDataValuesdash[i];++i) {
    if ( undefined === sum[c[0]] ) {        
       sum[c[0]] = c;
    }
    else {
        sum[c[0]][1] += c[1];
    }
}
result = Object.keys(sum).map(function(val) { return sum[val]});

alert(JSON.stringify(result));

Here is a simple solution, not very sophisticated but gets the job done.

var a = [
    ['Anantapur', 10, '#C21466'],
    ['Anantapur', 20, '#A983D0'],
    ['Chittoor', 30, '#A993D0'],
    ['Anantapur', 30, '#544DDF'],
    ['Anantapur', 4, '#A994D0'],
    ['Chittoor', 40, '#544BDF']
];

var findDuplicatesAndSum = function(inptArr) {
    var duplicateIndex = {};
    var outputArr = [];
    for (var i = 0; i < inptArr.length; i++) {
        var item = inptArr[i];
        var collisionIndex = duplicateIndex[item[0]];
        if (collisionIndex > -1) {
            outputArr[collisionIndex][1] += item[1];
        } else {
            outputArr.push(item);
            duplicateIndex[item[0]] = outputArr.length - 1;
        }
    }
    console.log(outputArr);
    return outputArr;
};

findDuplicatesAndSum(a);

This code might helps.

var xDataValuesdash =  [    
	[ 'Anantapur', 10, '#C21466' ],
    [ 'Anantapur', 20, '#A983D0' ],
    [ 'Chittoor', 30, '#A993D0' ],
    [ 'Anantapur', 30, '#544DDF' ],
    [ 'Anantapur', 4, '#A994D0' ],
    [ 'Chittoor', 40, '#544BDF' ]  ];
var new_DataValuesdash = [];
for(var i=0; i < xDataValuesdash.length;i++){
	if(new_DataValuesdash[xDataValuesdash[i][0]] == undefined) {
        new_DataValuesdash[xDataValuesdash[i][0]] = xDataValuesdash[i];
    }
    else {
        // new_DataValuesdash[xDataValuesdash[i][0]] = [];
        new_DataValuesdash[xDataValuesdash[i][0]][1] = new_DataValuesdash[xDataValuesdash[i][0]][1] + xDataValuesdash[i][1];
    }
}
console.log(new_DataValuesdash);

You can use for..of loop, Array.prototype.some(), Array.prototype.forEach()

var xDataValuesdash =  [    [ 'Anantapur', 10, '#C21466' ],
                            [ 'Anantapur', 20, '#A983D0' ],
                            [ 'Chittoor', 30, '#A993D0' ],
                            [ 'Anantapur', 30, '#544DDF' ],
                            [ 'Anantapur', 4, '#A994D0' ],
                            [ 'Chittoor', 40, '#544BDF' ]  ];


var res = [];
for (var prop of xDataValuesdash) {
  !res.some(value => value && value[0] === prop[0])
  ? res.push(prop)
  : res.forEach(value => {
      if (value[0] === prop[0]) value[1] += prop[1]
    });      
}

console.log(res);

In this, we are first paring the index values and then find the total sum of duplicate elements-

  function sumOfRepeatedElements(numbers){
    let repeatedElementsArr = [];
    for(let i = 0; i < numbers.length; i++){
        if(numbers.indexOf(numbers[i]) !== numbers.lastIndexOf(numbers[i])){
            repeatedElementsArr.push(numbers[i])
        }
    }
    const sumArr = [...new Set(repeatedElementsArr)];
    return sumArr.reduce((acc,curr) => acc+curr,0)
}
console.log(sumOfRepeatedElements([1,2,3,4,3,5,6,5,8]));    // 3+5=8
console.log(sumOfRepeatedElements([2,2,3,4,3,5,6,5,7]));    // 2+3+5=10

发布评论

评论列表(0)

  1. 暂无评论