1

I am looking for a cleaner and more efficient solution in javascript to compare two arrays and create a third one.

So I have two arrays :

var array1 = [
    [{
    id: 1,
    enabled: false

  }],
  [{
    id: 2,
    enabled: true,
  }],
  [{
    id: 10,
    enabled: false
  }]
]

var array2 = [
    {
    id_from_array1: 10,
    data: true
  },
  {
    id_from_array1: 20,
    data: false
  },
  {
    id_from_array1: 1,
    data: true
  }
]

And i want to extract from the second array the IDs that are not present in the first array, so for now my solution is to create a third array with a double loop to compare the values ​​of the first two arrays :

var array3 = [];

for (var i = 0; i < array2.length; i++) {
  for (var y = 0; y < array1.length; y++) {
      if (array2[i].id_from_array1 === array1[y][0].id) {
        array3.push(array2[i])
    }
  }
}

the fiddle

can we do better ?

Thx!

1
  • By extract I meant delete, and by better I mean indeed with less code and more efficient Commented Feb 12, 2018 at 11:17

2 Answers 2

3

Create an array of id from array1 then .filter the array 2 based on the previous id array;

var ids = array1.map( el => el[0].id );
ids = Array.from(new Set(ids)); // Get unique ids as set are always unique
var array3 = array2.filter( el => ids.indexOf(el.id_from_array1)!==-1);
console.log(array3);

var array1 = [
    [{
    id: 1,
    enabled: false

  }],
  [{
    id: 2,
    enabled: true,
  }],
  [{
    id: 10,
    enabled: false
  }]
]

var array2 = [
    {
    id_from_array1: 10,
    data: true
  },
  {
    id_from_array1: 20,
    data: false
  },
  {
    id_from_array1: 1,
    data: true
  }
];

var ids = array1.map( el => el[0].id );
var array3 = array2.filter( el => ids.indexOf(el.id_from_array1)!==-1);
console.log(array3);

Sign up to request clarification or add additional context in comments.

4 Comments

Thx for your answer, luckily, I can indeed use ES6 in my project without transpilers, I'm going to compare performance on big data
@spitfire378 sure :)
@spitfire378 check the slight optimization I did. Now I am picking the unique ids from array1.
Nice @void thx, your last optimization significantly increases performance on the big data I'm processing
0

you can use find function as follows:

var array3 = [];
array2.find(function(element1) {
  var matched = array1.find(function(element2) {
    return element2[0].id == element1.id_from_array1;
  });
  if (matched != null) array3.push(matched);
});

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.