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?
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.
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.
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.
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.
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With