Array.push() 和唯一项

Array.push() and unique items

本文关键字:唯一 push Array      更新时间:2023-09-26

我有一个简单的将唯一值推入数组的情况。它看起来像这样:

  this.items = [];
  add(item) {
    if(this.items.indexOf(item) > -1) {
      this.items.push(item);
      console.log(this.items);
    }
  }

看起来很简单,对吧?不,正如它看起来的那样。它不添加任何值。我确信这是我这边的某种愚蠢的错误,但我似乎找不到它。

是的,这是一个小错误。

if(this.items.indexOf(item) === -1) {
    this.items.push(item);
    console.log(this.items);
}

您可以使用 ES6 中的 Set 结构来使代码更快、更具可读性:

// Create Set
this.items = new Set();
add(item) {
    this.items.add(item);
    // Set to array
    console.log([...this.items]);
}

try .include((

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true

所以像

const array = [1, 3];
if (!array.includes(2))
    array.push(2);

但是,请注意页面底部的浏览器兼容性。

使用 Set

this.items = new Set();
this.items.add(1);
this.items.add(2);
this.items.add(1);
this.items.add(2);
console.log(Array.from(this.items)); // [1, 2]
如果您

正在寻找一个衬垫

对于基元

(this.items.indexOf(item) === -1) && this.items.push(item);

对于对象

this.items.findIndex((item: ItemType) => item.var === checkValue) === -1 && this.items.push(item);

如果你使用 Lodash,看看_.union函数:

let items = [];
items = _.union([item], items)

你的逻辑是说,"如果这个项目已经存在,那就添加它。它应该与此相反。

将其更改为...

if (this.items.indexOf(item) == -1) {
    this.items.push(item);
}

我想 ES6 已经设置了数据结构,您可以将其用于唯一条目

你必须

使用 === -1,如果它等于 -1,即 item 在你的数组中不可用:

  this.items = [];
  add(item) {
    if(this.items.indexOf(item) === -1) {
      this.items.push(item);
      console.log(this.items);
    }
  }

这可以通过单行代码来实现。

this.items = this.items.includes(item) ? this.items : [...this.items, item];

尽可能简单!

  let items = [];
  const addItem = (item) => {
    items = [...new Set([...items, item])]
  };
var helper = {};
for(var i = 0; i < data.length; i++){
  helper[data[i]] = 1; // Fill object
}
var result = Object.keys(helper); // Unique items

在数组中推送始终唯一的值

ab = [
     {"id":"1","val":"value1"},
     {"id":"2","val":"value2"},
     {"id":"3","val":"value3"}
   ];

var clickId = [];
var list = JSON.parse(ab);
$.each(list, function(index, value){
    if(clickId.indexOf(value.id) < 0){
        clickId.push(value.id);
    }
});

所以不确定这是否回答了您的问题,但索引您添加的项目一直返回-1。 不熟悉 js,但似乎这些项目这样做是因为它们还没有在数组中。我为您制作了一些修改后的代码。

this.items = [];
add(1);
add(2);
add(3);
document.write("added items to array");
document.write("<br>");
function  add(item) {
        //document.write(this.items.indexOf(item));
    if(this.items.indexOf(item) <= -1) {
      this.items.push(item);
      //document.write("Hello World!");
    }
}
document.write("array is : " + this.items);

https://jsfiddle.net/jmpalmisano/Lnommkbw/2/

简单地使用带有 concat 的新 Set((。性能最高的大部分和更新:

console.log([...new Set(["hey", "we", "have", "array"].concat(["hey", "we", "add", "these", "too", "but without second hey, we, have :)"]))])

如果要以不区分大小写的方式添加元素,请对数组执行此操作;即:

["hey", "we", "HaVe", "ArrAy"].filter(r => r !== '').map(r => r.toUpperCase())

这将检查是否为空元素:

.filter(r => r !== '')

将检查不区分大小写:

.map(r => r.toUpperCase()