Friday, September 26, 2025
HomeLanguagesJavascriptHow to get the same value from another array and assign to...

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

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 ]


RELATED ARTICLES

Most Popular

Dominic
32321 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6690 POSTS0 COMMENTS
Nicole Veronica
11857 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11912 POSTS0 COMMENTS
Shaida Kate Naidoo
6802 POSTS0 COMMENTS
Ted Musemwa
7073 POSTS0 COMMENTS
Thapelo Manthata
6761 POSTS0 COMMENTS
Umr Jansen
6768 POSTS0 COMMENTS