Cómo obtener valores únicos en una matriz [duplicado]

Resuelto Astronaut asked hace 12 años • 20 respuestas

¿Cómo puedo obtener una lista de valores únicos en una matriz? ¿Tengo que usar siempre una segunda matriz o hay algo similar al hashmap de Java en JavaScript?

Usaré JavaScript y jQuery únicamente. No se pueden utilizar bibliotecas adicionales.

Astronaut avatar Jun 28 '12 21:06 Astronaut
Aceptado

Aquí hay una solución mucho más limpia para ES6 que veo que no está incluida aquí. Utiliza el operador Set y spread :...

var a = [1, 1, 2];

[... new Set(a)]

que regresa[1, 2]

Charles Clayton avatar Feb 08 '2017 21:02 Charles Clayton

O para aquellos que buscan un one-liner (sencillo y funcional) compatible con los navegadores actuales :

let a = ["1", "1", "2", "3", "3", "1"];
let unique = a.filter((item, i, ar) => ar.indexOf(item) === i);
console.log(unique);
Expandir fragmento

Actualización 2021. Recomendaría consultar la respuesta de Charles Clayton ; a partir de los cambios recientes en JS, hay formas aún más concisas de hacer esto.

Actualización 18-04-2017

Parece que 'Array.prototype.includes' ahora tiene soporte generalizado en las últimas versiones de los navegadores principales ( compatibilidad ).

Actualización 29-07-2015:

Hay planes en proceso para que los navegadores admitan un método estandarizado 'Array.prototype.includes', que aunque no responde directamente a esta pregunta; a menudo está relacionado.

Uso:

["1", "1", "2", "3", "3", "1"].includes("2");     // true

Pollyfill ( soporte del navegador , fuente de mozilla ):

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1.
        // NOTE: === provides the correct "SameValueZero" comparison needed here.
        if (o[k] === searchElement) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}
Josh Mc avatar Apr 25 '2014 00:04 Josh Mc

Como hablé de ello en los comentarios de la respuesta de @Rocket, también puedo proporcionar un ejemplo que no utilice bibliotecas. Esto requiere dos nuevas funciones prototipo, containsyunique

Array.prototype.contains = function(v) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === v) return true;
  }
  return false;
};

Array.prototype.unique = function() {
  var arr = [];
  for (var i = 0; i < this.length; i++) {
    if (!arr.contains(this[i])) {
      arr.push(this[i]);
    }
  }
  return arr;
}

var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];
var uniques = duplicates.unique(); // result = [1,3,4,2,8]

console.log(uniques);
Expandir fragmento

Para mayor confiabilidad, puede reemplazar containscon la cuña de MDN indexOfy verificar si cada elemento indexOfes igual a -1: documentación

jackwanders avatar Jun 28 '2012 14:06 jackwanders

Una sola línea, JavaScript puro

Con sintaxis ES6

list = list.filter((x, i, a) => a.indexOf(x) === i)

x --> item in array
i --> index of item
a --> array reference, (in this case "list")

ingrese la descripción de la imagen aquí

Con sintaxis ES5

list = list.filter(function (x, i, a) { 
    return a.indexOf(x) === i; 
});

Compatibilidad del navegador : IE9+

Vamsi avatar Sep 01 '2016 13:09 Vamsi