Open In App

How to get the same value from another array and assign to object of arrays ?

Last Updated : 10 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to get the same value from another array and assign it to an 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 the array

We can do this by using the following methods:

Method 1: Using forEach() and push()

In this method, we will be using the forEach() and push(), includes() method of the array to get the same value from another array and assign it to the object of arrays.

Example:

Javascript




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


Output

[ 1, 2, 4, 453 ]


Method 2: Using filter() and push()

In this method, we will use the filter(), push(), and includes() of array to get the same value from another array and assign it to the object of arrays.

Example:

Javascript




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


Output

[ 1, 2, 4, 453 ]




Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads