Delete all elements in array javascript

How to remove items from an array in JavaScript

Last week, we looked at different ways to add items to an array in JavaScript. Today, you’ll learn how to remove single as well as multiple elements from an array in JavaScript.

JavaScript provides many ways to remove elements from an array. You can remove an item:

If you already know the array element index, just use the Array.splice() method to remove it from the array. This method modifies the original array by removing or replacing existing elements and returns the removed elements if any. Let us say you got the following array, and you want to remove the element at index 2 ( Cherry ):

const fruits = ['Apple', 'Orange', 'Cherry', 'Mango', 'Banana']; const removed = fruits.splice(2, 1); console.log(fruits); // ['Apple', 'Orange', 'Mango', 'Banana'] console.log(removed); // ['Cherry'] 
const fruits = ['Apple', 'Orange', 'Cherry', 'Mango', 'Banana']; const removed = fruits.splice(2, 2); console.log(fruits); // ['Apple', 'Orange', 'Banana'] console.log(removed); // ['Cherry', 'Mango'] 

The second argument of Array.splice() is the number of elements to remove. Remember that Array.splice() modifies the array in place and returns a new array containing the elements that have been removed.

If you know the element value, first use the Array.indexOf() method to find the index of the element in the array and then use Array.splice() to remove it. Here is an example:

const fruits = ['Apple', 'Orange', 'Cherry', 'Mango', 'Banana']; const index = fruits.indexOf('Mango'); if (index > -1)  fruits.splice(index, 1); > console.log(fruits); // ['Apple', 'Orange', 'Cherry', 'Banana'] 

Note that the Array.indexOf() method returns the index of the first matching element. If the array contains multiple elements with the same values, only the first element will be removed. To filter out all elements with the same value from an array, use the Array.filter() method instead:

const fruits = ['Apple', 'Mango', 'Cherry', 'Mango', 'Banana']; const filtered = fruits.filter(fruit => fruit !== 'Mango'); console.log(filtered); // ['Apple', 'Cherry', 'Banana'] 

The Array.filter() method creates a new array populated with all array elements that pass a certain condition. This method doesn’t modify the original array. Take a look at this article to learn more about the Array.filter() method.

The Array.pop() method can be used to remove an element from the end of an array. This method removes the last element and returns it:

const fruits = ['Apple', 'Mango', 'Cherry', 'Mango', 'Banana']; const elem = fruits.pop(); console.log(fruits); // ['Apple', 'Mango', 'Cherry', 'Mango'] console.log(elem); // Banana 

The Array.shift() method works exactly like Array.pop() except that it removes an element from the start of the array. All other elements are shifted to a lower index.

const fruits = ['Apple', 'Mango', 'Cherry', 'Mango', 'Banana']; const elem = fruits.shift(); console.log(fruits); // ['Mango', 'Cherry', 'Mango', 'Banana'] console.log(elem); // Apple 
const fruits = ['Apple', 'Mango', 'Cherry', 'Mango', 'Banana']; // empty an array fruits.length = 0 console.log(fruits); // [] 

Take a look at this article to learn more about JavaScript arrays and how to use them to store multiple pieces of information in one single variable. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Remove all items after an index

Use Array.length to set a new size for an array, which is faster than Array.splice to mutate:

var array = ['mario','luigi','kong', 1, 3, 6, 8]; array.length=2; alert(array); // shows "mario,luigi"; 

Why is it faster? Because .splice has to create a new array containing all the removed items, whereas .length creates nothing and «returns» a number instead of a new array.

To address .splice usage, you can feed it a negative index, along with a huge number to chop off the end of an array:

var array = ['mario','luigi','kong']; array.splice(-1, 9e9); alert(array); // shows "mario,luigi"; 

Could reducing length cause a memory leak or does the javascript engine handle this? — Ok, according to the ECMAScript specs this is clearly defined and handled correctly, the elements will get deleted. stackoverflow.com/questions/31547315/…

Pro tip you can use array.splice(0, Infinity) . I mean i would be hard pressed to believe you could have an array with more than 9000000000 items in it. But you do feel cool when you have a reason to use the Infinity keyword in JS 🙂

Would the array.length trick work for say. getting only 6,8 in the sample array? Because I don’t see how you can get the last elements in an array using the length trick. That should only work with splice correct?

@Hangfish: if you only want to get elements and not mutate the array, use .slice(-2) . If you need to collect elements you remove, use .splice()

If you are using this to trim an array to a max length and if you’re not certain your array is longer than the max, you probably will want to check first: const maxLen = 3; if (array.length > maxLen) array.length = maxLen; Otherwise you will end up adding empty values to an array that is already short enough.

Though assigning a shorter value to the array length(as @dandavis said) is the fastest and simplest way to remove trailing element from an array, you can also do that using a similar method like splice which is known as slice. Like following:

array = ['mario', 'luigi', 'kong']; array = array.slice(0, 2); //Need to assign it to the same or another variable console.log(array); //["mario", "luigi"]

As you can see you need to store the returned value from slice method. To understand ‘why’, here are the major distinction between slice and splice method:

  • The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.
  • The splice() method changes the original array and slice() method doesn’t change the original array.

Here is a small benchmark (jsperf.com/remove-all-array-elements-after-a-given-index) comparing solutions given for this question.

To remove all items after an index:

var array = ['mario','luigi','kong'], index = 1; // your index here array = array.splice(index + 1, array.length - (index + 1) ); // 3 - (1+1) = 1 // 1 is the remaining number of element(s) in array // hence, splice 1 after index 

You need to +1 since splice starts removing at the index.

I think you misunderstood the usage of Array.prototype.splice() . It already does what you asked for (remove everything after an index, read below paragraph for correction) and it does return the deleted values. I think you got confused with the returned value as the current value of the array.

Array.prototype.splice() however, removes the provided index value too, which is basically equivalent of setting the length of the array. So if you call it as array.splice(2) , it’ll set the length to 2 and everything including the values at index 2 and after will be deleted. This is provided that the current length of the array is greater than the first parameter provided to Array.prototype.splice() .

const array = ['mario','luigi','kong']; const deletedItem = array.splice(1); console.log(array); // ['mario'] console.log(deletedItem); // ['luigi','kong']

For more information: refer to the MDN doc.

Источник

Читайте также:  Python package for django
Оцените статью