How to get the same value from another array and assign to object of arrays?
To get the same value from another array and insert it into an object of the array we need to.
- Compare each and every element of two arrays
- Return the matched element
- Add the element or object into the object of array
Before jumping into the code, you can read the following articles. It will help you to understand it better,
- Array forEach() method
- Array push() method
- Array includes() method
- Array filter() method
- ES6 Arrow function
Method 1: Using forEach() and push(), includes() method of array.
Javascript
<script> // Define first array let arr1 = [1, 2, 3, 4, 5, 77, 876, 453]; // Define second array let arr2 = [1, 2, 45, 4, 231, 453]; // Create a empty object of array let result = []; // Checked the matched element between two // array and add into result array arr1.forEach( val => arr2.includes(val) && result.push(val) ); // Print the result on console console.log( result ); </script> |
Output:
1, 2, 4, 453
Method 2: filter(), push() and includes() of array.
Javascript
<script> // Define first array let arr1 = [1, 2, 3, 4, 5, 77, 876, 453]; // Define second array let arr2 = [1, 2, 45, 4, 231, 453]; / Checked the matched element between two array // and add into the result array let result = arr1.filter(val => arr2.includes(val) ); // Print the result on console console.log( result ); </script> |
Output:
1, 2, 4, 453