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:
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
let arr1 = [1, 2, 3, 4, 5,
77, 876, 453];
let arr2 = [1, 2, 45, 4, 231, 453];
let result = [];
arr1.forEach(val =>
arr2.includes(val) && result.push(val));
console.log(result);
|
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
let arr1 = [1, 2, 3, 4, 5,
77, 876, 453];
let arr2 = [1, 2, 45, 4, 231, 453];
let result = arr1.filter(
val => arr2.includes(val));
console.log(result);
|