Array.push() 如果不存在?

IT技术 javascript arrays json push not-exists
2021-02-11 08:34:15

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

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

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

我怎样才能做到这一点?

6个回答

对于字符串数组(但不是对象数组),您可以通过调用检查项目是否存在.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)

@EmilPedersen - 不是真的。尝试if (a.indexOf({ name: "tom", text: "tasty" })!=-1) a.push({ name: "tom", text: "tasty" })两次。它将两次添加“类似”对象。
2021-03-25 08:34:15
不知道为什么这没有被标记为正确。它不使用任何外部组件,不需要创建扩展并且非常简单。操作问题的完美答案。
2021-03-30 08:34:15
在最初的问题中,数组的值是对象,而不是字符串(如果值是对象,则此解决方案不起作用)。
2021-04-05 08:34:15
这不是一个正确的答案,为什么被接受?它只适用于 Js 数组,而不适用于数组中的对象。
2021-04-10 08:34:15
这个答案应该被删除,因为它客观上是错误的,但仍然吸引了最多的赞成票。
2021-04-12 08:34:15

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

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

index === -1 ? arrayObj.push({your_object}) : console.log("object already exists")
 
如果不存在,则与在数组中添加元素最相关
2021-03-28 08:34:15

您可以使用自定义方法扩展 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; 
});
最好使用 JavaScript 1.6 方法 IndexOf 而不是 inArray 来扩展 Array 原型。
2021-03-18 08:34:15
我认为你的camparer(比较器?)应该有两个参数,这会简化当附加值是内联的而不是你可以在函数中访问的变量时的情况。array.pushIfNotExist({ name: "tom", text: "tasty" }, function(a,b){ return a.name === b.name && a.text === b.text; });
2021-03-25 08:34:15
Array.findIndex() 是一个内置的 JS 函数,它将实现与您的代码相同的功能。
2021-04-01 08:34:15
我想知道为什么这不是语言原生的 - 忘记它是如何实现的 - “仅在唯一时添加”的想法是如此基本以至于被认为存在。
2021-04-04 08:34:15
直接扩展内置对象是一种不好的做法。
2021-04-10 08:34:15

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

var cleanArray = $.unique(clutteredArray);

你可能也对 makeArray 感兴趣

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

除了我不确定 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;
}
你可以使用 lodash _.indexOf,这将在 IE8 中工作
2021-03-26 08:34:15
来自 jQuery 链接:Note that this only works on arrays of DOM elements, not strings or numbers.此外,indexOf 在 IE8 中不起作用 :(
2021-03-30 08:34:15

像这样?

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)
array.find是个坏主意,因为它搜索整个数组。使用findIndex,它只搜索直到第一次出现。
2021-03-30 08:34:15
@K48 根据这个:stackoverflow.com/a/33759573/5227365 “find”在找到项目后停止
2021-03-30 08:34:15