Javascript 只推送数组中的唯一元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31709845/
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-23 07:04:18  来源:igfitidea点击:

push only unique elements in an array

javascriptjqueryarrays

提问by smtp

I have array object(x) that stores json (key,value) objects. I need to make sure that x only takes json object with unique key. Below, example 'id' is the key, so i don't want to store other json objects with 'item1' key.

我有存储 json (key,value) 对象的数组 object(x)。我需要确保 x 只接受具有唯一键的 json 对象。下面,示例 'id' 是键,所以我不想用 'item1' 键存储其他 json 对象。

x = [{"id":"item1","val":"Items"},{"id":"item1","val":"Items"},{"id":"item1","val":"Items"}]    

var clickId = // could be "item1", "item2"....
var found = $.inArray(clickId, x);  //
if(found >=0)
{
    x.splice(found,1);
}
else{
    x.push(new Item(clickId, obj)); //push json object
}

回答by stackoverfloweth

would this accomplish what you're looking for? https://jsfiddle.net/gukv9arj/3/

这会完成你正在寻找的吗?https://jsfiddle.net/gukv9arj/3/

x = [
    {"id":"item1","val":"Items"},
    {"id":"item1","val":"Items"},
    {"id":"item2","val":"Items"}
];    

var clickId = [];
var list = JSON.parse(x);
$.each(list, function(index, value){
    if(clickId.indexOf(value.id) === -1){
        clickId.push(value.id);
    }
});

回答by Dave

You can't use inArray()because you are searching for an object.

您无法使用,inArray()因为您正在搜索object.

I'd recommend rewriting a custom find using Array.some()as follows.

我建议使用Array.some()如下方式重写自定义查找。

var x = [{"id":"item1","val":"Items"},{"id":"item1","val":"Items"},{"id":"item1","val":"Items"}]    

var clickId = "item1";
var found = x.some(function(value) {
  return value.id === clickId;
});
alert(found);

回答by Populus

This is how I would do it in pure javascript.

这就是我在纯 javascript 中的做法。

var x = [{"id":"item1","val":"Items"},{"id":"item1","val":"Items"},{"id":"item1","val":"Items"}];

function unique(arr, comparator) {
  var uniqueArr = [];
  for (var i in arr) {
    var found = false;
    for (var j in uniqueArr) {
      if (comparator instanceof Function) {
        if (comparator.call(null, arr[i], uniqueArr[j])) {
          found = true;
          break;
        }
      } else {
        if (arr[i] == uniqueArr[j]) {
          found = true;
          break;
        }
      }
    }
    if (!found) {
      uniqueArr.push(arr[i]);
    }
  }
  return uniqueArr;
};

u = unique(x, function(a,b){ return a.id == b.id; });
console.log(u);

y = [ 1,1,2,3,4,5,5,6,1];
console.log(unique(y));

回答by Ron Sims II

JS objects are great tools to use for tracking unique items. If you start with an empty object, you can incrementally add keys/values. If the object already has a key for a given item, you can set it to some known value that is use used to indicate a non-unique item.

JS 对象是用于跟踪独特项目的绝佳工具。如果您从一个空对象开始,您可以逐步添加键/值。如果对象已经具有给定项目的键,您可以将其设置为某个已知值,用于指示非唯一项目。

You could then loop over the object and push the unique items to an array.

然后,您可以遍历对象并将唯一项推送到数组。

var itemsObj = {};
var itemsList = [];
x = [{"id":"item1","val":"foo"},
    {"id":"item2","val":"bar"},
    {"id":"item1","val":"baz"},
    {"id":"item1","val":"bez"}];

for (var i = 0; i < x.length; i++) {
    var item = x[i];
    if (itemsObj[item.id]) {
        itemsObj[item.id] = "dupe";
    }
    else {
        itemsObj[item.id] = item;
    }
}

for (var myKey in itemsObj) {
    if (itemsObj[myKey] !== "dupe") {
        itemsList.push(itemsObj[myKey]);
    }
}

console.log(itemsList);

See a working example here: https://jsbin.com/qucuso

在此处查看工作示例:https: //jsbin.com/qucuso

If you want a list of items that contain only the first instance of an id, you can do this:

如果你想要一个只包含一个 id 的第一个实例的项目列表,你可以这样做:

var itemsObj = {};
var itemsList = [];
x = [{"id":"item1","val":"foo"},
    {"id":"item2","val":"bar"},
    {"id":"item1","val":"baz"},
    {"id":"item1","val":"bez"}];

for (var i = 0; i < x.length; i++) {
    var item = x[i];
    if (!itemsObj[item.id]) {
        itemsObj[item.id] = item;
        itemsList.push(item);
    }
}

console.log(itemsList);

回答by TheCleverIdiot

This is late but I did something like the following:

这很晚了,但我做了如下的事情:

let MyArray = [];
MyArray._PushAndRejectDuplicate = function(el) {
    if (this.indexOf(el) == -1) this.push(el)
    else return;
} 

MyArray._PushAndRejectDuplicate(1); // [1]
MyArray._PushAndRejectDuplicate(2); // [1,2]
MyArray._PushAndRejectDuplicate(1); // [1,2]

回答by BruceJo

Create a very readable solution with lodash.

使用 lodash 创建一个非常易读的解决方案。

x = _.unionBy(x, [new Item(clickId, obj)], 'id');

x = _.unionBy(x, [new Item(clickId, obj)], 'id');