Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Make an array of another array\'s duplicate values in JavaScript
In JavaScript, finding duplicate values between two arrays is a common task. This article demonstrates how to create an array containing elements that exist in both arrays using built-in array methods.
What is an Array in JavaScript?
An array is an object that stores multiple elements in a single variable. Arrays in JavaScript are ordered collections that can hold any data type and provide methods like filter() and indexOf() for manipulation.
const array = [201, 202, 405];
Understanding the Logic
To find duplicate values between two arrays, we use the filter() method on the first array and indexOf() to check if each element exists in the second array. When indexOf() returns a value other than -1, the element is present in both arrays.
Using filter() and indexOf() Methods
// Define two arrays with some common elements
const arr1 = [11, 12, 13, 14, 15, 16, 17, 18, 19];
const arr2 = [13, 16, 19, 2];
// Find duplicates using filter and indexOf
const duplicates = arr1.filter((value) => {
return arr2.indexOf(value) !== -1;
});
console.log("Duplicates:", duplicates);
Duplicates: [13, 16, 19]
Alternative Method Using includes()
The includes() method provides a more readable alternative to indexOf():
const arr1 = [11, 12, 13, 14, 15, 16, 17, 18, 19];
const arr2 = [13, 16, 19, 2];
// Using includes() method for better readability
const duplicates = arr1.filter(value => arr2.includes(value));
console.log("Duplicates with includes():", duplicates);
Duplicates with includes(): [13, 16, 19]
Comparison of Methods
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
indexOf() |
Good | O(n×m) | All browsers |
includes() |
Better | O(n×m) | ES2016+ |
Time and Space Complexity
Both methods have O(n×m) time complexity, where n is the length of the first array and m is the length of the second array. The space complexity is O(k), where k is the number of duplicate elements found.
Conclusion
Using filter() with either indexOf() or includes() provides an effective way to find duplicate values between arrays. The includes() method offers better readability for modern JavaScript environments.
