Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - remove array element on condition

Tags:

javascript

I was wondering how I'd go about implementing a method in javascript that removes all elements of an array that clear a certain condition. (Preferably without using jQuery)

Ex.

ar = [ 1, 2, 3, 4 ]; ar.removeIf( function(item, idx) {     return item > 3; }); 

The above would go through each item in the array and remove all those that return true for the condition (in the example, item > 3).

I'm just starting out in javascript and was wondering if anyone knew of a short efficient way to get this done.

--update--

It would also be great if the condition could work on object properties as well.

Ex.

ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ]; ar.removeIf( function(item, idx) {     return item.str == "c"; }); 

Where the item would be removed if item.str == "c"

--update2--

It would be nice if index conditions could work as well.

Ex.

ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ]; ar.removeIf( function(item, idx) {     return idx == 2; }); 
like image 662
dk123 Avatar asked Apr 14 '13 04:04

dk123


People also ask

How do you remove an element from an array based on condition?

To remove array element on condition with JavaScript, we can use the array filter method. let ar = [1, 2, 3, 4]; ar = ar.

How do you remove an element from an array based on value?

We can use the following JavaScript methods to remove an array element by its value. indexOf() – function is used to find array index number of given value. Return negavie number if the matching element not found. splice() function is used to delete a particular index value and return updated array.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

Can we delete array element in JavaScript?

Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.


1 Answers

You can use Array filter method.

The code would look like this:

ar = [1, 2, 3, 4];  ar = ar.filter(item => !(item > 3));  console.log(ar) // [1, 2, 3]
like image 184
Klaster_1 Avatar answered Sep 21 '22 00:09

Klaster_1