Skip to content
Related Articles

Related Articles

Improve Article
How to get the same value from another array and assign to object of arrays?
  • Last Updated : 12 Mar, 2021

To get the same value from another array and insert it into an object of the array we need to.

  1. Compare each and every element of two arrays
  2. Return the matched element
  3. 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, 

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :