0

I have two arrays containing some objects and I need to know how to combine them and exclude any duplicates. (For example, the object that contains apple: 222 from the second array should be excluded, if it already exists in the first array.)

Check below:

var arr1 = [
    {apple: 111, tomato: 55},
    {apple: 222, tomato: 55}
]

var arr2 = [
    {apple: 222, tomato: 55},
    {apple: 333, tomato: 55}
]

I want the result to be like this:

   var res = [
    {apple: 111, tomato: 55},
    {apple: 222, tomato: 55},
    {apple: 333, tomato: 55}
]

How can I do that in javascript?

5
  • Those "inner arrays" are javascript objects, FWIW. Commented Oct 16, 2013 at 11:06
  • Please post array literals (and not PHP) Commented Oct 16, 2013 at 11:06
  • Your array begin by '(' and finish by '}' ??? Commented Oct 16, 2013 at 11:08
  • Look up Array's concat method. Commented Oct 16, 2013 at 11:08
  • Not sure why you changed the example code, but I've amended my answer to fit. Commented Oct 16, 2013 at 13:26

2 Answers 2

1

Does this solution fit with your needs (demo) ?

var res, i, item, prev;

// merges arrays together
res = [].concat(arr1, arr2);

// sorts the resulting array based on the apple property
res.sort(function (a, b) {
    return a.apple - b.apple;
});

for (i = res.length - 1; i >= 0; i--) {
    item = res[i];

    // compares each item with the previous one based on the apple property
    if (prev && item.apple === prev.apple) {

        // removes item if properties match
        res.splice(i, 1);
    }
    prev = item;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could write a dedupe function.

if (!Array.prototype.dedupe) {
  Array.prototype.dedupe = function (type) {
    for (var i = 0, l = this.length - 1; i < l; i++) {
      if (this[i][type] === this[i + 1][type]) {
        this.splice(i, 1);
        i--; l--;
      }
    }
    return this;
  }
}

function combine(arr1, arr2, key) {
  return arr1
    .concat(arr2)
    .sort(function (a, b) { return a[key] - b[key]; })
    .dedupe(key);   
}

var combined = combine(arr1, arr2, 'apple');

Fiddle.

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.