What\'s the best method to get the index of an array which contains objects?
Imagine this scenario:
var hello = {
hello: \'world\',
foo: \'ba
Using the ES6 findIndex method, without lodash or any other libraries, you can write:
function deepIndexOf(arr, obj) {
return arr.findIndex(function (cur) {
return Object.keys(obj).every(function (key) {
return obj[key] === cur[key];
});
});
}
This will compare the immediate properties of the object, but not recurse into the properties.
If your implementation doesn't provide findIndex
yet (most don't), you can add a light polyfill that supports this search:
function deepIndexOf(arr, obj) {
function findIndex = Array.prototype.findIndex || function (pred) {
for (let i = 0; i < this.length; ++i) {
if (pred.call(this, this[i], i)) {
return i;
}
}
return -1;
}
return findIndex.call(arr, function (cur) {
return Object.keys(obj).every(function (key) {
return obj[key] === cur[key];
});
});
}
(from my answer on this dupe)