When dealing with OBJECT values
If you are using indexOf
with objects, it is important to compare them with the exact same object reference. You must have the identical reference to successfully remove it from the array where it was previously added.
Objects are compared based on references, while primitives are compared based on values. For further details, refer to How to determine equality for two JavaScript objects?
const array = [];
const obj = { '3': '4' };
array.push({ '1': '2' });
array.push(obj);
const index = array.indexOf(obj);
console.log(index);
When working with PRIMITIVE values
If you are dealing with an array of primitive values, you can safely use indexOf
because primitives are compared based on their values as shown below:
const array = ['1', '2', '3'];
console.log(array.indexOf('3'));
1) An alternative approach is to use findIndex
with hasOwnProperty
to achieve a similar result. Credits to pilchard
for this suggestion.
const array = [];
array.push({ '1': '2' });
array.push({ '3': '4' });
const index = array.findIndex((o) => o.hasOwnProperty('3'));
if (index > -1) {
array.splice(index, 1);
}
console.log(array);
2) Another option is to use findIndex
to locate the index of an object that contains 3
as a key.
const array = [];
array.push({ '1': '2' });
array.push({ '3': '4' });
const index = array.findIndex((o) => Object.keys(o).some((k) => k === '3'));
if (index > -1) {
array.splice(index, 1);
}
console.log(array);