How to compare elements in array objects using javascript

Viewed 68

I am new to javascript usage. I have a requirement to compare the field from two different array objects which are having list as below.

Array - A

[
  {
    "id": "xyz",
    "number": "123",
    "place": "Here",
    "phone": "9090909090"     
  },
  {
    "id": "abc",
    "number": "456",
    "place": "There",
    "phone": "9191919191"    
  },
 ]
 
 Array - B
 
 [
 {
    "element1" : "ert",
    "id1":"iii",
    "element2":"erws",
    "element3":"234"
    
 }
,
 {
    "element1" : "uio",
    "id1":"xyz",
    "element2":"puy",
    "element3":"090"
 }
]

The scenario is to compare for each 'id' in the list of array A, with the list of Array B to field 'id1'

Example -

I need to check from Array A -> 'id:xyz' matches the array B object field 'id1'. Array A - id: xyz should match with id1: xyz in Array B If the match occurs I need to pull out complete object from the array list A.

here id:xyz matches with id1:xyz

then pull out as below

[
  {
    "id": "xyz",
    "number": "123",
    "place": "Here",
    "phone": "9090909090"     
  }
 ]

Please help me with the suggestions to make this work using javascript.

2 Answers

const A = [
  {
    "id": "xyz",
    "number": "123",
    "place": "Here",
    "phone": "9090909090"     
  },
  {
    "id": "abc",
    "number": "456",
    "place": "There",
    "phone": "9191919191"    
  },
];

const B = [
  {
    "element1" : "ert",
    "id1":"iii",
    "element2":"erws",
    "element3":"234"
  },
  {
    "element1" : "uio",
    "id1":"xyz",
    "element2":"puy",
    "element3":"090"
  }
];

const C = A.filter(a => B.some(b => b.id1 === a.id));
console.log(C);

// the usage of `const` here means that arrA cannot be re-declared
// this is good for data that should not be changed
const arrA = [{
    "id": "xyz",
    "number": "123",
    "place": "Here",
    "phone": "9090909090"
  },
  {
    "id": "abc",
    "number": "456",
    "place": "There",
    "phone": "9191919191"
  },
];

const arrB = [{
    "element1": "ert",
    "id1": "iii",
    "element2": "erws",
    "element3": "234"

  },
  {
    "element1": "uio",
    "id1": "xyz",
    "element2": "puy",
    "element3": "090"
  }
];

// slow method for long lists, fine for short lists or if there are duplicates
// compares each entry in array A to each entry in array B
const out1 = arrA.filter(x => arrB.some(y => x.id === y.id1));
console.log("Example 1: \n", out1);

// faster for long lists
// creates a set of unique values for array B's id1 parameter, ignores duplicates
// then checks that set for each entry in array A
const setB = arrB.reduce((a, b) => {
  a.add(b.id1);
  return a;
}, new Set());
const out2 = arrA.filter(x => setB.has(x.id));
console.log("Example 2: \n", out2)
.as-console-wrapper { min-height: 100% } /* this is just to make the stack overflow output prettier */

Related