Skip to content Skip to sidebar Skip to footer

Detect The Element In An Array

I have two arrays like var array1 = [ { id: '1', name: 'test' }, { id: '2', name: 'test2' }, { id: '3', name: 'test3' }

Solution 1:

It’s time for ECMA5

var array1 = [
    {
      id: '1',
      name: 'test',
      foo: {
        bar: 'bar',
        quux: 'quux'
      }
    },
    {
      id: '2',
      name: 'test2'
    },
    {
      id: '3',
      name: 'test3'
    }
];

functionequal(objA, objB) {
    if(Object.keys(objA).length !== Object.keys(objB).length) {
        returnfalse;
    }

    var areEqual = Object.keys(objA).every(function(key) {
        if(typeof objA[key] === "object") {
            returnequal(objA[key], objB[key]);
        }
        return objA[key] === objB[key];
    });

    return  areEqual;
}

functionhasElement(array, element) {
    return array.some(function(el) {
        returnequal(el, element);
    });
}

console.log(hasElement(array1, {
  id: '1',
  name: 'test',
  foo: {
    bar: 'bar',
        quux: 'quux'
    }
}));

Solution 2:

Assuming the IDs in array2 are all unique, I would create an object whose keys are the IDs:

var obj2 = {};
for (var i = 0; i < array2.length; i++) {
    obj2[array2[i].id] = array2[i];
}

Then I would use this to find matching elements:

for (var i = 0; i < array1.length; i++) {
    if (obj2[array1[i].id]) {
        alert("find!");
    }
}

Post a Comment for "Detect The Element In An Array"