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条回答
We Are One
2楼-- · 2019-01-04 00:02

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)
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-04 00:03

In case you need something simple without wanting to extend the Array prototype:

// 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);
}
查看更多
Viruses.
4楼-- · 2019-01-04 00:04

This is working func for an objects comparison. In some cases you might have lot of fields to compare. Simply loop the array and call this function with a existing items and new item.

 var objectsEqual = function (object1, object2) {
        if(!object1 || !object2)
            return false;
        var result = true;
        var arrayObj1 = _.keys(object1);
        var currentKey = "";
        for (var i = 0; i < arrayObj1.length; i++) {
            currentKey = arrayObj1[i];
            if (object1[currentKey] !== null && object2[currentKey] !== null)
                if (!_.has(object2, currentKey) ||
                    !_.isEqual(object1[currentKey].toUpperCase(), object2[currentKey].toUpperCase()))
                    return false;
        }
        return result;
    };
查看更多
叛逆
5楼-- · 2019-01-04 00:06

You could extend the Array prototype with a custom method:

// 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; 
});
查看更多
放荡不羁爱自由
6楼-- · 2019-01-04 00:08

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

var cleanArray = $.unique(clutteredArray);

you might be interested in makeArray too

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.

Array.prototype.pushUnique = function (item){
    if(this.indexOf(item) == -1) {
    //if(jQuery.inArray(item, this) == -1) {
        this.push(item);
        return true;
    }
    return false;
}
查看更多
Explosion°爆炸
7楼-- · 2019-01-04 00:13

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

[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.

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 }])
查看更多
登录 后发表回答