如果两个值都不存在,我如何推入数组?这是我的数组:

[
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]

如果我试图再次推入数组的名字:“tom”或文本:“tasty”,我不希望发生任何事情…但如果这两个都不存在那么我就输入。push()

我该怎么做呢?


当前回答

你可以用一个自定义方法扩展Array原型:

// check if an element exists in array using a comparer function
// comparer : function(currentElement)
Array.prototype.inArray = function(comparer) { 
    for(var i=0; i < this.length; i++) { 
        if(comparer(this[i])) return true; 
    }
    return false; 
}; 

// adds an element to the array if it does not already exist using a comparer 
// function
Array.prototype.pushIfNotExist = function(element, comparer) { 
    if (!this.inArray(comparer)) {
        this.push(element);
    }
}; 

var array = [{ name: "tom", text: "tasty" }];
var element = { name: "tom", text: "tasty" };
array.pushIfNotExist(element, function(e) { 
    return e.name === element.name && e.text === element.text; 
});

其他回答

推送后删除重复项

如果你已经有一个包含重复项的数组,将对象数组转换为字符串数组,然后使用Set()函数消除重复项:

let arr_obj = [
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" }
]

let arr_str = arr_obj.map(JSON.stringify)

let arr_unique = [...new Set(arr_str)].map(JSON.parse) 

推前检查

如果你到目前为止没有重复的元素,你想在推入一个新元素之前检查重复:

let arr_obj = [
    { name: "tom", text: "tasty" },
    { name: "tim", text: "tusty" }
]

let new_obj = { name: "tom", text: "tasty" }

let arr_str = arr_obj.map(JSON.stringify)

!arr_str.includes(JSON.stringify(new_obj)) && arr_obj.push(new_obj)

如果你需要一些简单的东西,而不想扩展数组原型:

// Example array
var array = [{id: 1}, {id: 2}, {id: 3}];

function pushIfNew(obj) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].id === obj.id) { // modify whatever property you need
      return;
    }
  }
  array.push(obj);
}

像这样的吗?

var item = "Hello World";
var array = [];
if (array.indexOf(item) === -1) array.push(item);

与对象

var item = {name: "tom", text: "tasty"}
var array = [{}]
if (!array.find(o => o.name === 'tom' && o.text === 'tasty'))
    array.push(item)

这个问题有点老了,但我的选择是

    let finalTab = [{id: 1, name: 'dupont'}, {id: 2, name: 'tintin'}, {id: 3, name:'toto'}]; // Your array of object you want to populate with distinct data
    const tabToCompare = [{id: 1, name: 'dupont'}, {id: 4, name: 'tata'}]; // A array with 1 new data and 1 is contain into finalTab
    
    finalTab.push(
      ...tabToCompare.filter(
        tabToC => !finalTab.find(
          finalT => finalT.id === tabToC.id)
      )
    ); // Just filter the first array, and check if data into tabToCompare is not into finalTab, finally push the result of the filters

    console.log(finalTab); // Output : [{id: 1, name: 'dupont'}, {id: 2, name: 'tintin'}, {id: 3, name: 'toto'}, {id: 4, name: 'tata'}];

我知道这是一个非常老的问题,但如果你使用ES6,你可以使用一个非常小的版本:

[1,2,3].filter(f => f !== 3).concat([3])

非常简单,首先添加一个过滤器,删除项目-如果它已经存在,然后通过concat添加它。

下面是一个更现实的例子:

const myArray = ['hello', 'world']
const newArrayItem

myArray.filter(f => f !== newArrayItem).concat([newArrayItem])

如果你的数组包含对象,你可以像这样调整过滤器函数:

someArray.filter(f => f.some(s => s.id === myId)).concat([{ id: myId }])