简体   繁体   中英

How to check for the existence of objects in an array

I am trying to add only unique named objects (no duplicates) to an array and in order to do that, I have to first check to see if the object already exists in the array. Unfortunately, all of my attempts keep adding duplicate objects to the array. I can check the array for each object, one-by-one, to see if the object I want to add is already in the array, and if it is, I do nothing. So, I'm checking for a match between my item.ORG and the object's name in the array. That helps to see if it is a match, but if it doesn't match, I don't want to add the new object to the array, because it might have a match with an object that is further down the array. My latest attempt, below, doesn't work either.

//constructor for OrgObj that goes in ORRArr
function OrgObj(itemOrg) {
    this.name = itemOrg;
    this.count = 0;
    this.url_status_list = [];
}

var ORGArr = [];

$.each(_items, function(index, item) {
            var weFoundIt = true;

            if (ORGArr.length === 0) {
                ORGArr.push(new OrgObj(item.ORG));
            } else {
                for (var i = 0; i < ORGArr.length; i++) {
                    if (item.ORG === ORGArr[i].name) {
                        break;
                    } else {
                        weFoundIt = false; {

                        }
                    }
                    if (weFountIt === false) {
                        ORGArr.push(new OrgObj(item.ORG));
                    }
                });

In your loop you should initialize weFoundIt to false and only set it to true if you found it. Also place the check behind the loop and there is also a typo in the last conditional ( fount instead of found ). Here is a working example: https://jsfiddle.net/y4b80wcc/

A shorter alternative would be https://jsfiddle.net/xdwzfghr/1/

if(ORGArr.map(function(x){return x.name;}).indexOf(item.ORG) === -1) {
    ORGArr.push(new OrgObj(item.ORG))
}

I would use filter method.

//constructor for OrgObj that goes in ORRArr
function OrgObj(itemOrg) {
  this.name = itemOrg;
  this.count = 0;
  this.url_status_list = [];
}

var ORGArr = [];
var _items = [new OrgObj('A'), new OrgObj('B'), new OrgObj('C'), new OrgObj('B'), new OrgObj('B'), new OrgObj('A'), new OrgObj('D')]


var foundNamesLookup = {};
ORGArr = _items.filter(function(item) {
  if (foundNamesLookup [item.name]) {
    return false;
  }
  foundNamesLookup [item.name] = true;
  return true;
});

console.log(ORGArr);

EDIT: https://jsfiddle.net/yoy0s7cL/ (see results in console)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM