Javascript Array.push() 如果不存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1988349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:15:58  来源:igfitidea点击:

Array.push() if does not exist?

javascriptarraysjsonpushnot-exists

提问by tarnfeld

How can I push into an array if neither values exist? Here is my array:

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

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

If I tried to push again into the array with either name: "tom"or text: "tasty", I don't want anything to happen... but if neither of those are there then I want it to .push()

如果我尝试使用name: "tom"or再次推入数组text: "tasty",我不希望发生任何事情......但如果这两者都不存在,那么我希望它.push()

How can I do this?

我怎样才能做到这一点?

采纳答案by Darin Dimitrov

You could extend the Array prototype with a custom method:

您可以使用自定义方法扩展 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; 
});

回答by Ji?í Zahálka

For an array of strings (but not an array of objects), you can check if an item exists by calling .indexOf()and if it doesn't then just pushthe item into the array:

对于字符串数组(但不是对象数组),您可以通过调用检查项目是否存在.indexOf(),如果不存在,则只需项目入数组:

var newItem = "NEW_ITEM_TO_ARRAY";
var array = ["OLD_ITEM_1", "OLD_ITEM_2"];

array.indexOf(newItem) === -1 ? array.push(newItem) : console.log("This item already exists");

console.log(array)

回答by Ashish Yadav

It is quite easy to do using the Array.findIndexfunction, which takes a function as an argument:

使用Array.findIndex函数很容易,它接受一个函数作为参数:

var a = [{name:"bull", text: "sour"},
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]
var index = a.findIndex(x => x.name=="bob")
// here you can check specific property for an object whether it exist in your array or not

if (index === -1){
    a.push({your_object});
}
else console.log("object already exists")

回答by MistereeDevlord

http://api.jquery.com/jQuery.unique/

http://api.jquery.com/jQuery.unique/

var cleanArray = $.unique(clutteredArray);

you might be interested in makeArray too

你可能也对 makeArray 感兴趣

The previous example is best in saying that check if it exists before pushing. I see in hindsight it also states you can declare it as part of the prototype (I guess that's aka Class Extension), so no big enhancement below.

前面的例子最好说在推送之前检查它是否存在。事后看来,它还指出您可以将其声明为原型的一部分(我想这就是类扩展),因此下面没有大的增强。

Except I'm not sure if indexOf is a faster route then inArray? probably.

除了我不确定 indexOf 是否比 inArray 更快?大概。

Array.prototype.pushUnique = function (item){
    if(this.indexOf(item) == -1) {
    //if(jQuery.inArray(item, this) == -1) {
        this.push(item);
        return true;
    }
    return false;
}

回答by Ronen Rabinovici

Use a js library like underscore.jsfor these reasons exactly. Use: union: Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.

正是出于这些原因,使用像underscore.js这样的 js 库。使用: union:计算传入数组的并集:一个或多个数组中按顺序排列的唯一项的列表。

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]

回答by Ronnie Royston

Like this?

像这样?

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

With object

有对象

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

回答by Michael J. Zoidl

I know this is a very old question, but if you're using ES6 you can use a very small version:

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

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

Very easy, at first add a filter which removes the item - if it already exists, and then add it via a concat.

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

Here is a more realistic example:

这是一个更现实的例子:

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

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

If you're array contains objects you could adapt the filter function like this:

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

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

回答by Gopala raja naika

Push dynamically

动态推送

var a = [
  {name:"bull", text: "sour"},
  {name: "tom", text: "tasty" },
  {name: "Jerry", text: "tasty" }
]

function addItem(item) {
  var index = a.findIndex(x => x.name == item.name)
  if (index === -1) {
    a.push(item);
  }else {
    console.log("object already exists")
  }
}

var item = {name:"bull", text: "sour"};
addItem(item);

In simple method

用简单的方法

var item = {name:"bull", text: "sour"};
a.findIndex(x => x.name == item.name) == -1 ? a.push(item) : console.log("object already exists")

If the array contains only primitive types/ simple array

如果数组只包含原始类型/简单数组

var b = [1, 7, 8, 4, 3];
var newItem = 6;
b.indexOf(newItem) === -1 && b.push(newItem);

回答by Michael McQuade

I would suggest you use a Set,

我建议你使用Set

Sets only allow unique entries, which automatically solves your problem.

集合只允许唯一的条目,这会自动解决您的问题。

Sets can be declared like so:

集合可以这样声明:

const baz = new Set(["Foo","Bar"])

回答by Eric Valero

Easy code, if 'indexOf' returns '-1' it means that element is not inside the array then the condition '=== -1' retrieve true/false.

简单的代码,如果 'indexOf' 返回 '-1',则表示该元素不在数组内,则条件 '=== -1' 检索真/假。

The '&&' operator means 'and', so if the first condition is true we push it to the array.

'&&' 运算符的意思是 'and',所以如果第一个条件为真,我们将它推送到数组中。

array.indexOf(newItem) === -1 && array.push(newItem);