tar*_*eld 226 javascript arrays json push not-exists
如果两个值都不存在,我如何进入数组?这是我的数组:
[
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" }
]
Run Code Online (Sandbox Code Playgroud)
如果我试图再次推到与在阵列name: "tom"
或text: "tasty"
,我不希望发生什么事......但是,如果这两个时间都不存在那么我想它.push()
我怎样才能做到这一点?
Jiř*_*lka 381
对于字符串数组(但不是对象数组),您可以通过调用检查项是否存在.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)
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 105
您可以使用自定义方法扩展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;
});
Run Code Online (Sandbox Code Playgroud)
ash*_*dav 81
使用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")
Run Code Online (Sandbox Code Playgroud)
Mis*_*ord 40
http://api.jquery.com/jQuery.unique/
var cleanArray = $.unique(clutteredArray);
Run Code Online (Sandbox Code Playgroud)
你可能也对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;
}
Run Code Online (Sandbox Code Playgroud)
Ron*_*ici 24
出于这些原因,请使用像underscore.js这样的js库.使用:union:计算传入数组的并集:按顺序存在于一个或多个数组中的唯一项列表.
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]
Run Code Online (Sandbox Code Playgroud)
Ron*_*ton 24
像这样?
var item = "Hello World";
var array = [];
if (array.indexOf(item) === -1) array.push(item);
Run Code Online (Sandbox Code Playgroud)
有了对象
var item = {name: "tom", text: "tasty"}
var array = [{}]
if (!array.find(o => o.name === 'tom' && o.text === 'tasty'))
array.push(item)
Run Code Online (Sandbox Code Playgroud)
Eri*_*ero 22
简单的代码,如果 'indexOf' 返回 '-1',则表示该元素不在数组内,则条件 '=== -1' 检索真/假。
'&&' 运算符的意思是 'and',所以如果第一个条件为真,我们将它推送到数组中。
array.indexOf(newItem) === -1 && array.push(newItem);
Run Code Online (Sandbox Code Playgroud)
Mic*_*ade 17
我建议你使用Set,
集合只允许唯一的条目,这会自动解决您的问题。
集合可以这样声明:
const baz = new Set(["Foo","Bar"])
Run Code Online (Sandbox Code Playgroud)
Mic*_*idl 14
我知道这是一个非常古老的问题,但如果您使用的是ES6,则可以使用非常小的版本:
[1,2,3].filter(f => f !== 3).concat([3])
Run Code Online (Sandbox Code Playgroud)
非常简单,首先添加一个删除项目的过滤器 - 如果它已经存在,然后通过concat添加它.
这是一个更现实的例子:
const myArray = ['hello', 'world']
const newArrayItem
myArray.filter(f => f !== newArrayItem).concat([newArrayItem])
Run Code Online (Sandbox Code Playgroud)
如果您的数组包含对象,您可以调整过滤器函数,如下所示:
someArray.filter(f => f.some(s => s.id === myId)).concat([{ id: myId }])
Run Code Online (Sandbox Code Playgroud)
Gop*_*ika 10
动态推送
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);
Run Code Online (Sandbox Code Playgroud)
用简单的方法
var item = {name:"bull", text: "sour"};
a.findIndex(x => x.name == item.name) == -1 ? a.push(item) : console.log("object already exists")
Run Code Online (Sandbox Code Playgroud)
我的选择是.includes()
按照@Darrin Dimitrov 的建议使用扩展 Array.prototype:
Array.prototype.pushIfNotIncluded = function (element) {
if (!this.includes(element)) {
this.push(element);
}
}
Run Code Online (Sandbox Code Playgroud)
只记得includes
来自 es6 并且不适用于 IE:https :
//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
归档时间: |
|
查看次数: |
290309 次 |
最近记录: |