2

I'm trying to merge duplicate entries in an array of objects by creating a new array.

I don't know how to check for duplicated without looping through the new array, which then messes me up when trying to push stuff because it does it every time for the outer loop.

How should I do this properly?

var arr=[0];
for (var k in data) {
    var name = data[k].name;
    var item = data[k];
    //check if already in array
    for (var l in arr){
        if (arr[l].name == name){
            arr[l].value = arr[l.value] + ';;' + item.value;
        } else {
            arr.push(item);
        }
    }
}
4
  • Do you consider using Lodash? Your problem can be solved in one line. :) Commented Apr 18, 2016 at 0:06
  • Also note that for..in is for looping objects, not arrays. Commented Apr 18, 2016 at 0:06
  • 1
    How would I go about doing this with lodash? Commented Apr 18, 2016 at 0:08
  • See my answer below. Commented Apr 18, 2016 at 0:09

2 Answers 2

1

With Lodash

var arr = _.uniqBy(data, 'name');
Sign up to request clarification or add additional context in comments.

Comments

0

Not quite sure if I'm answering your question right, but you could use .indexOf() to solve this. indexOf returns the position of an element in an array, or -1 if it doesn't exist: http://www.w3schools.com/jsref/jsref_indexof_array.asp

var oldArr = [1,2,2,2,3,4,5];
var newArr = [];

for (var i = 0; i < oldArr.length; i++) {
    if (newArr.indexOf(oldArr[i]) == -1) {
        newArr.push(oldArr[i]);
    }
}

console.log(newArr);

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.