Tamas Farago
Tamas Farago

Reputation: 139

How to compare 2 arrays and leave the one that has a similar value in React?

I have 2 arrays:

array1 = 
[{package_id: 4, is_checked: 1, images: Array(0)}]

array2 = 
[
{package_id: 3, width: "80", length: "120", height: "200", weight: "222", …},
{package_id: 4, width: "210", length: "70", height: "76", weight: "83", …}
]

The result I want to get is:

array3 = [{package_id: 4, width: "210", length: "70", height: "76", weight: "83", …}]

As you can see I removed the object where the package_id didn't match. How can I achieve this?

Upvotes: 0

Views: 55

Answers (3)

buzatto
buzatto

Reputation: 10382

you could store your array1 ids at a Set first to avoid nested iteration while you filter, since Set has method O(1) complexity. This would give better performance than calling filter and iterating over array1 for each array2 element:

  const ids = new Set()
  array1.forEach(({package_id}) => ids.add(package_id))
  const array3 = array2.filter(({package_id}) => ids.has(package_id))

Upvotes: 0

DDomen
DDomen

Reputation: 1878

Assuming you filter array2 by the array1 package_id

array3 = array2.filter(e1 => array1.some(e2 => e1.package_id == e2.package_id))

Upvotes: 0

Orelsanpls
Orelsanpls

Reputation: 23505

You can use Array.filter in order to keep only the elements that have a matching package_id with at least one element of array_1.

const array1 = [{
  package_id: 4,
  is_checked: 1,
  images: Array(0),
}];

const array2 = [{
    package_id: 3,
    width: '80',
    length: '120',
    height: '200',
    weight: '222',
  },
  {
    package_id: 4,
    width: '210',
    length: '70',
    height: '76',
    weight: '83',
  },
];

const filteredData = array2.filter(({
  package_id,
}) => array1.some(x => x.package_id === package_id));

console.log(filteredData);

Upvotes: 3

Related Questions