Delete all element in array javascript

MODERN METHODS TO REMOVE ITEMS FROM ARRAYS IN JAVASCRIPT

Arrays in JavaScript are special objects that store items sequentially, that is, they store items one after another in memory. They are high-level, list-like objects. You can actually think of them as lists of items.

All items in an array have an index which indicates the position of that item in the array. The item in the first position has an index of 0 then next has an index of 1 etc. For this reason, JavaScript’s array indexes are zero-based.
Items in JavaScript arrays can be accessed using their index.
We can find the index of an item in an array using a special method called the indexOf.

You can simply think of JavaScript arrays as an ordered set of values that you refer to with a name and an index

const listOfAnimals = [ «dog», «cat», «rat», «fish», «rabbit» ] console.log(listOfAnimals) // returns the listOfAnimals array console.log(listOfAnimals[0]) // gets the item at index 0 console.log(listOfAnimals[2]) // gets the third item which is the item at index 2 let itemPosition = listOfAnimals.indexOf(«rat») // gets the index of the item passed. here «rat» console.log(itemPosition) // displays the index of «rat» in the listOfAnimals array

The total number of items in an array is the length of that array.
The length property is special. It always returns the index of the last element plus one.

Читайте также:  Дизайн input file css

const evenNumbers = [2,4,6,8,10,12] console.log(evenNumbers.length) // returns the length of the evenNumbers array

JavaScript arrays are the most used data structure and because they organize items sequentially, it is super easy to access the first and last item. Hence deleting these items are very easy in JavaScript.

2. Array.prototype.shift()

The shift() method removes the first element in an array (that is the item at the index of zero). It also re-orders the remaining elements in the array and decrements the array length by one. Finally, it returns the removed item.

const languages = [ «PHP», «Python», «Rust», «C++», «C», «Ruby», «JavaScript» ] const removedLanguage = languages.shift() console.log(removedLanguage) // returns «PHP» console.log(languages) // returns new array without «PHP»

3. Array.prototype.pop()

The pop() method is the opposite of the shift(). It removes the last element of the array.
The index of the last element in the array is the length of the array minus one. The pop() method, also decrements the array length by one and returns the removed element.

const frameworks = [ «React.js», «Angular», «Vue.js», «Express.js», «Ember.js» ] const removedFramework = frameworks.pop() console.log(removedFramework) // returns «Ember.js» console.log(frameworks) // returns new array without «Ember.js»

4. The Delete Operator

Both the pop() and the shift() methods give us a way to remove elements from an array from pre-set position viz: the last or first positions respectively. While they are great, we do not get the freedom of deleting elements from any other position. What if we want to delete elements at a certain index which is neither the first nor the last?

The delete operator is great for this.
Unlike pop() and shift() the delete operator returns the new array.

const items = [«eggs», «meat», «vegetables», «salad», «rice», «fish» ] delete items[3] console.log(items) console.log(items.length) console.log(items[3])

One thing that must be noted before one should use the delete method is that it does not change the length of the array as seen above. It removes the specified element and adds undefined in its place.

5. Array.prototype.splice()

If the delete operator is not very suitable for you because it does not update the array length, another built-in array method you can use is the splice() method.

The splice() method is a very powerful built-in array method that can be used to remove array elements at any index. It can also be used to add elements or replace an existing element. But we will just stick to removing elements from an array. It can remove multiple elements from an array unlike pop() and shift() that removes one element at a time.
Lastly the splice() method returns a new array containing the deleted element/elements.

The splice() method can take up to three parameters for our use case it needs only two. The first specifies the index to start deleting from the second specifies how many elements to remove from the array

//remove single element const numbersInWords = [ «one», «two», «three», «four», «five», «dozen», «six» ] const arrayWithDeletedItems = numbersInWords.splice(5, 1) //returns [«dozen»] // remove multiple elements const mammals = [«man», «dog», «rat», «cat», «fish», «snake», «fly»] const nonMammals = mammals.splice(4, 3) // return [«fish», «snake», «fly»] console.log(numbersInWords) console.log(arrayWithDeletedItems) console.log(mammals) console.log(nonMammals)

6. Array.prototype.filter()

We saw the power of splice() above as we used it to elements from any index in an array. But with splice() we could only delete multiple elements in series.

const numList = [1,2,3,4,5,6,»Half-dozen»,7,8,9,10,11,12,»one-dozen»,13,14,15,16,17,18,19,20] const result = numList.splice(7, 5) console.log(result) console.log(numList)

What if we want to delete all the words from our numList array above? since the words are not in series in the above array splice() is not the best fit. Except we are implementing our own remove() method where we can use it under the hood. A good option is to use the filter() since we are deleting all instance of a string in the array.

The filter() methods calls a provided callback function once for each element in an array and returns a new array of elements that passes the test implemented in the callback function.

const numList = [1,2,3,4,5,6,»Half-dozen»,7,8,9,10,11,12,»one-dozen»,13,14,15,16,17,18,19,20] pureNumList = numList.filter(item => typeof item !== «string») // returns a list of numbers pureEvenNumber = numList.filter(item => typeof item !==»string» && item % 2 === 0) // returns a list of only even numbers. console.log(numList) console.log(pureNumList) console.log(pureEvenNumber)

Noticed the power of the filter() method, how it allows us to remove multiple elements from an array regardless of their index. Also, notice how we can combine conditions in the callback function implementation to target multiple elements.

const numList = [1,2,3,4,5,6,»Half-dozen»,7,8,9,10,11,12,»one-dozen»,13,14,15,16,17,18,19,20] pureEvenNumber = numList.filter(item => typeof item !==»string» && item % 2 === 0) // returns a list of only even numbers. console.log(pureEvenNumber)

A Masterpiece

There are still other ways to do this in JavaScript, truly at this point, it should boil down to a developer’s implementation of his own custom function. Maybe you dream of a remove() method of your own. I will leave you with a masterpiece from John Resig. (The creator of jQuery).

// Array Remove — By John Resig (MIT Licensed) Array.prototype.remove = function(from, to) < var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); >; const numList = [1,2,3,4,5,6,»Half-dozen»,7,8,9,10,11,12,»one-dozen»,13,14,15,16,17,18,19,20] numList.remove(13) numList.remove(6) console.log(numList) // returns a new array with only numbers.

8. Closing Thoughts

These are a nice collection of ways to remove items from an array but it is by no means an exhaustive list. As I said developers can always come up with something novel. If you do have a custom helper function to achieve this task, you are more than welcome to share it in the comment section below.

Источник

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.

Источник

Оцените статью