DEV Community

Cover image for Adding and removing items from an array in JavaScript
coder4life
coder4life

Posted on

Adding and removing items from an array in JavaScript

There many different ways of adding items from and array and removing them again. For adding you might want to look into: push(), unshift(), concat(), and destructuring. For removing you could take a closer look at shift(), pop(), and splice().

Here are some code snippets for adding:

const cars = ['Audi', 'BMW', 'Ford'];

cars.push('Fiat'); // add one to the end
cars.push('Tesla', 'VW'); // add multiple to the end

cars.unshift('Peugeot'); // add to beginning

const moreCars = ['Honda', 'Bentley'];

cars.push(...['Toyota', 'Volvo']); // add another array to the end
const allCars = cars.concat(moreCars);

Here are some code snippets for removing:

const cars = ['Audi', 'BMW', 'Ford'];

cars.pop() // last car gone
cars.shift() // first car gone
cars.splice(2, 2); // cars at index gone

// You can also remove by value like this:

for (const i = 0; i < cars.length; i++) { 
   if (cars[i] === 'BMW') {
     cars.splice(i, 1); 
     i--;
   }
}

const newCars = cars.filter(carName => {
    return carName !== 'Ford';
});

How would you go about doing some like this? What do you think would be best from a performance perspective?

Discussion (0)