0

I have an object with duplicate values and I want to count all those which have the same value and remove them.

var myArray = [{nr: 'bbc',}, {nr: 'bbc'}, {nr: 'bbc'}, {nr: ccc}];

from this array I want to create another array but remove the duplicated values and count them to be like this.

var myArray = [{nr: 'bbc',amount: 3}}, {nr: ccc,amount: 1}]; 
3
  • And the question is? Commented Aug 29, 2014 at 11:51
  • 1
    Why are you storing as {nr:'bbc'} instead of just storing a list of the 'bbc' Commented Aug 29, 2014 at 11:52
  • I need something like this. Commented Aug 29, 2014 at 11:58

2 Answers 2

1

You could probably use a better format

var count = {};
for(var i = 0; i < myArray.length; ++i) {
  if(typeof count[myArray[i].nr] == 'undefined') {
    count[myArray[i].nr] = 0;
  }

  ++count[myArray[i].nr];
}

and this wound yield somehing like:

count = {
  bcc: 3,
  ccc: 1
};

if you still need it with the structure you specified, then:

var newArray = [];
for(var k in count) {
  newArray.push({
    nr: k,
    amount: count[k]
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that will but I need a array with the key and the amount in the same obj.
0

If you want the same structure, this will work for you

var newArray = [];
for (var i = 0; i < myArray.length; i++) {
    var matched = false;
    for (var j = 0; j < newArray.length; j++) {
        if(myArray[i].nr === newArray[j].nr){
            matched = true;
            newArray[j].amount++;
            break;
        }
    };
    if(!matched)
        newArray.push({nr:myArray[i].nr,amount:1});
};
console.log(newArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.