In case of OBJECT values
If you are using indexOf
with objects then you have to compare it with the exact same object. You need to have exact same reference to remove it from the array in which you have added prior.
Objects are compared with references and primitives are compared with values. For more info, 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);
In case of PRIMITIVE values
If the input is array of primitive values then you could have used indexOf
because primitives are compared with value as:
const array = ['1', '2', '3'];
console.log(array.indexOf('3'));
1) You can use findIndex
with hasOwnProperty
to get the same result. Thanks 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) You can use findIndex
to find the index of the object who has 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);
6
solved Javascript Array Push and then Splice it not working