0

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?

0

3 Answers 3

3

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

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

Comments

0

Assuming you filter array2 by the array1 package_id

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.