Home > Web Front-end > JS Tutorial > How to Efficiently Find and Return Unique Values in a JavaScript Array?

How to Efficiently Find and Return Unique Values in a JavaScript Array?

Mary-Kate Olsen
Release: 2024-12-28 10:24:10
Original
959 people have browsed it

How to Efficiently Find and Return Unique Values in a JavaScript Array?

Finding Unique Values in JavaScript Arrays

When dealing with arrays in JavaScript, it's often desirable to remove duplicate values to ensure uniqueness. Here's a common problem encountered with JavaScript arrays:

var numbers = [1, 2, 3, 4, 5, 1, 2];
numbers.getUnique(); // [1, 2, 3, 4, 5] (incorrectly includes 1 and 2)
Copy after login

The provided prototype method, Array.prototype.getUnique, attempts to filter out duplicates but fails when it encounters a zero value.

To understand the issue, let's inspect the code:

Array.prototype.getUnique = function() {
  var o = {}, a = [], i, e;
  for (i = 0; e = this[i]; i++) {o[e] = 1};
  for (e in o) {a.push (e)};
  return a;
};
Copy after login

The problem lies in the object o used to track unique values. When a number is inserted into o, it's converted to a string. However, for zero, this conversion results in the empty string ''.

Thus, when the second loop iterates over o, it encounters the empty string as a key and adds it to the a array. This results in the incorrect inclusion of duplicate values.

A Correct Solution for Unique Values

To accurately get unique values from an array, consider the following ES6 solution using the filter method:

function onlyUnique(value, index, array) {
  return array.indexOf(value) === index;
}

// usage example:
var numbers = [1, 2, 3, 4, 5, 1, 2];
var unique = numbers.filter(onlyUnique);

console.log(unique); // [1, 2, 3, 4, 5]
Copy after login

This function compares the index of each value in the array with the current index. If the index matches, it means the value is unique and is included in the filtered array. With this approach, all duplicate values are effectively removed.

The above is the detailed content of How to Efficiently Find and Return Unique Values in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template