So basically i want to remove the 3, with the 4. So its just only "1":"2" left.
const array = [];
array.push({ "1": "2" })
array.push({ "3": "4" })
const index = array.indexOf(3);
if (index > -1) {
array.splice(index, 1);
}
console.log(array)
So basically i want to remove the 3, with the 4. So its just only "1":"2" left.
const array = [];
array.push({ "1": "2" })
array.push({ "3": "4" })
const index = array.indexOf(3);
if (index > -1) {
array.splice(index, 1);
}
console.log(array)
You can use the Array.pop() method Array.prototype.pop() like this:
const array = [];
array.push({ 1: '2' });
array.push({ 2: '4' });
array.pop();
console.log(array);
Since you are pushing the whole object in the array after the two insertions your array would like something like this :
[ {"1":"2"}, {"3":"4"} ]
So when you perform the action indexOf, it does't return anything.
In order to get the desired result you can try using object and use delete to remove any property you don't want. Example
const obj = {}
obj["1"] = "2";
obj["3"] = "4"
console.log("original obj : ", obj)
delete obj["3"];
console.log("filtered obj : ", obj)
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);
filter
the objects. If an object's key matches your search key it doesn't get returned in the filtered array.
const arr = [];
arr.push({ 1: '2' })
arr.push({ 3: '4' })
function remove(arr, k) {
return arr.filter(obj => {
return Object.keys(obj)[0] !== k;
});
}
console.log(remove(arr, '3'));