spitfire378
spitfire378

Reputation: 89

Compare two arrays in javascript with specific ID

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!

Upvotes: 1

Views: 5489

Answers (2)

Hussam Kurd
Hussam Kurd

Reputation: 9166

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);
});

Upvotes: 0

void
void

Reputation: 36703

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);

Upvotes: 3

Related Questions