Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Array Push and then Splice it not working

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading