Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare values of an array, with the key of an array of objects

As the question indicates, I need to compare the values of an array of this type [1,2,3], with the values of a key of an array of objects [{id: 1, name: 'jhon'}, {id: 2 , name: 'max'}] in this case I want to compare it with the value of the id key, I write the following example of what I need:

if I have this array of objects:

[
   {
      id: 1
      name: 'jhon'
   },
   {
     id: 2,
     name: 'max'
   },
   {
     id: 3,
     name: 'fer'
   }
]

and I have this array:

[1,2,3,4,5]

I need to compare them and obtain the values that are not present in the array of objects, in the previous example the values 4 and 5 are not present in the array of objects, so I need to obtain a new array or the same, but with the values that do not they were, [4,5]

NOTE: this should also work if I have an array, only with numbers that are not present, for example [8,9], they should return those same values.

EDIT: it is possible to obtain in a new array those values that are only present in the array of objects. For example, with the arrays of the previous code:

[{id: 1, name: 'jhon'}, {id: 2, name: 'max'}, {id: 3, name: 'fer'}]

now this array would have the following values [1,4,5] with the previous answers I get the following array [4,5] what is correct. how can I get the values [2,3] in a new array.

like image 754
FeRcHo Avatar asked Jan 24 '26 10:01

FeRcHo


2 Answers

You can use filter and find

let arr1 = [{id: 1,name: 'jhon'},{id: 2,name: 'max'},{id: 3,name: 'fer'}]
let arr2 = [1, 2, 3, 4, 5];

let result = arr2.filter(o => !arr1.find(x => x.id === o));

console.log(result);

Update: This is basically the reverse of the first example. You filter the arr2 and check if the id exists on arr1. Then, use map to return the id

let arr1 = [{id: 1,name: 'jhon'},{id: 2,name: 'max'},{id: 3,name: 'fer'}]
let arr2 = [1,4,5];

let result = arr1.filter(o => !arr2.find(x => x === o.id)).map(o=>o.id);

console.log(result);

Doc: filter(), find()

like image 52
Eddie Avatar answered Jan 27 '26 00:01

Eddie


Create a Set from the ids of arr1 using Array.map(). Then filter arr2 by checking if the Set has the number:

const arr1 = [{"id":1,"name":"jhon"},{"id":2,"name":"max"},{"id":3,"name":"fer"}];
const arr2 = [1,2,3,4,5];
const arr3 = [1, 5];

const difference = (arr1, arr2, key) => {
  const arr1Values = new Set(key ? arr1.map(({ [key]: v }) => v) : arr1);

  return arr2.filter((n) => !arr1Values.has(n));
};

// array of primitives and array of objects
console.log(difference(arr1, arr2, 'id'));

// two arrays of primitives 
console.log(difference(arr3, arr2));
like image 38
Ori Drori Avatar answered Jan 26 '26 23:01

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!