Array.push() if does not exist?

2019-01-03 23:43发布

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()

How can I do this?

16条回答
疯言疯语
2楼-- · 2019-01-03 23:53

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

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")
查看更多
劫难
3楼-- · 2019-01-03 23:56

I used map and reduce to do this in the case where you wish to search by the a specific property of an object, useful as doing direct object equality will often fail.

var newItem = {'unique_id': 123};
var searchList = [{'unique_id' : 123}, {'unique_id' : 456}];

hasDuplicate = searchList
   .map(function(e){return e.unique_id== newItem.unique_id})
   .reduce(function(pre, cur) {return pre || cur});

if (hasDuplicate) {
   searchList.push(newItem);
} else {
   console.log("Duplicate Item");
}
查看更多
爷的心禁止访问
4楼-- · 2019-01-03 23:57

You can use the findIndex method with a callback function and its "this" parameter.

Note: old browsers don't know findIndex but a polyfill is available.

Sample code (take care that in the original question, a new object is pushed only if neither of its data is in previoulsy pushed objects):

var a=[{name:"tom", text:"tasty"}], b;
var magic=function(e) {
    return ((e.name == this.name) || (e.text == this.text));
};

b={name:"tom", text:"tasty"};
if (a.findIndex(magic,b) == -1)
    a.push(b); // nothing done
b={name:"tom", text:"ugly"};
if (a.findIndex(magic,b) == -1)
    a.push(b); // nothing done
b={name:"bob", text:"tasty"};
if (a.findIndex(magic,b) == -1)
    a.push(b); // nothing done
b={name:"bob", text:"ugly"};
if (a.findIndex(magic,b) == -1)
    a.push(b); // b is pushed into a
查看更多
霸刀☆藐视天下
5楼-- · 2019-01-03 23:58

Not sure about speed, but stringification + indexOf is a simple approach. Start with turning your array into a string:

let strMyArray = JSON.stringify(myArray);

Then for a series of attribute-value pairs you can use:

if (strMyArray.indexOf('"name":"tom"') === -1 && strMyArray.indexOf('"text":"tasty"') === -1) {
   myArray.push({ name: "tom", text: "tasty" });
}

Finding a whole object is simpler:

if (strMyArray.indexOf(JSON.stringify(objAddMe) === -1) { 
   myArray.push(objAddMe);
}
查看更多
Juvenile、少年°
6楼-- · 2019-01-04 00:00

In case anyone has less complicated requirements, here is my adaptation of the answer for a simple string array:

Array.prototype.pushIfNotExist = function(val) {
    if (typeof(val) == 'undefined' || val == '') { return; }
    val = $.trim(val);
    if ($.inArray(val, this) == -1) {
        this.push(val);
    }
};

Update: Replaced indexOf and trim with jQuery alternatives for IE8 compatability

查看更多
聊天终结者
7楼-- · 2019-01-04 00:02

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 push the item into the array:

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)

查看更多
登录 后发表回答