To find duplicate values in an array, you can use various approaches. Here are a couple of common methods:
Using a nested loop:
s
function findDuplicates(arr) {
var duplicates = [];
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j] && !duplicates.includes(arr[i])) {
duplicates.push(arr[i]);
}
}
}
return duplicates;
}
var array = [1, 2, 3, 4, 3, 2, 5, 6, 1];
var duplicates = findDuplicates(array);
console.log(duplicates); // Output: [2, 3, 1]
n this example, the
findDuplicates
function takes an array as input and uses a nested loop to compare each element with all subsequent elements. If a duplicate is found and it's not already in theduplicates
array, it is added to theduplicates
array.Using the
Set
data structure:
function findDuplicates(arr) {
var duplicates = [];
var uniqueSet = new Set();
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (uniqueSet.has(item) && !duplicates.includes(item)) {
duplicates.push(item);
} else {
uniqueSet.add(item);
}
}
return duplicates;
}
var array = [1, 2, 3, 4, 3, 2, 5, 6, 1];
var duplicates = findDuplicates(array);
console.log(duplicates); // Output: [2, 3, 1]
In this example, the
findDuplicates
function creates aSet
calleduniqueSet
to store unique elements encountered so far. For each element in the array, it checks if the element already exists in theuniqueSet
. If it does, and it's not already in theduplicates
array, it is added to theduplicates
array. If it doesn't exist in theuniqueSet
, it is added to theuniqueSet
.
Both methods provide the same result, which is an array containing the duplicate values from the original array.
You can also use the filter()
method in JavaScript to find duplicate values in an array. Here's an example:
function findDuplicates(arr) {
var duplicates = arr.filter(function(value, index, self) {
return self.indexOf(value) !== index;
});
return duplicates;
}
var array = [1, 2, 3, 4, 3, 2, 5, 6, 1];
var duplicates = findDuplicates(array);
console.log(duplicates); // Output: [2, 3, 1]
In this example, the findDuplicates
function uses the filter()
method on the input array. The filter()
method creates a new array that includes elements for which the provided callback function returns true
.
The callback function checks if the index of the current element value
in the original array is different from the first occurrence of that element in the array. If they are different, it means the element is a duplicate, and it is included in the duplicates
array.
The filter()
method simplifies the process of finding duplicates by leveraging the built-in array method. It provides a concise and expressive way to accomplish the task.
No comments:
Post a Comment