Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the single instance from an array in javascript? [duplicate]

Tags:

I need to find max number then remove it from array.(only single instance)

let array is

a=[91,65,91,88,26]

I am finding max using Math.max()

k=Math.max(...a)

Now using filter() it

a=a.filter(e => e!=k);

But its filtering both the instances of max number.

How to resolve it?

like image 261
YaSh Chaudhary Avatar asked Nov 27 '17 04:11

YaSh Chaudhary


People also ask

How do I remove a repeated value from an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

How do you remove duplicate array elements in JavaScript?

Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.

How do you remove a single value from an array?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.

How do you delete an instance of an array?

Pass the value of the element you wish to remove from your array into the indexOf() method to return the index of the element that matches that value in the array. Then make use of the splice() method to remove the element at the returned index.


1 Answers

Here are two simple ways to do it:

First way using splice()

a=[91,65,91,88,26];
a = a.sort();
a.splice(-1, 1);
console.log(a);

// Array [ 26, 65, 88, 91 ]

Second way using pop()

a=[91,65,91,88,26];
a = a.sort();
a.pop();
console.log(a);

// Array [ 26, 65, 88, 91 ]
like image 189
Ryan Griggs Avatar answered Sep 22 '22 13:09

Ryan Griggs