我需要找到数组中的最大值,然后将其从数组中删除(仅限单个实例)。
数组为:
a=[91,65,91,88,26]
我正在使用Math.max()函数来查找最大值。
k=Math.max(...a)
现在使用 filter() 函数进行筛选。
a=a.filter(e => e!=k);
但它过滤了最大数的两个实例。如何解决?
我需要找到数组中的最大值,然后将其从数组中删除(仅限单个实例)。
数组为:
a=[91,65,91,88,26]
我正在使用Math.max()函数来查找最大值。
k=Math.max(...a)
a=a.filter(e => e!=k);
以下是两种简单的方法:
第一种使用splice()函数:
a=[91,65,91,88,26];
a = a.sort();
a.splice(-1, 1);
console.log(a);
// Array [ 26, 65, 88, 91 ]
使用pop()的第二种方法
a=[91,65,91,88,26];
a = a.sort();
a.pop();
console.log(a);
// Array [ 26, 65, 88, 91 ]
a.sort().splice(-1, 1);
- fubar正如你所发现的,.filter()
会遍历整个数组,测试每个值是否符合过滤函数的条件。这不是你要完成的任务。
删除单个元素的关键是使用.splice()
。你的任务只是告诉splice需要删除哪些项:
a.splice(a.indexOf( k ), 1);
另外,您可以使用以下方式删除最后一个索引:
a.splice(a.lastIndexOf( k ), 1);
arr.splice(k, n)
的意思是“从索引k开始,移除接下来的n个元素”。a.sort().pop();
这将对数组进行排序,然后移除最后一个元素,也就是最大值。
findIndex
。k=Math.max(...a)
i=a.findIndex(el => el === k)
newArray = [...a.slice(0, i), ...a.slice(i+1)]
使用我所做的数组切片方式还可以确保我们不改变初始数组。
虽然我不建议在非常大的数组中使用此方法。
编写自己的函数来完成所有这些操作可以获得最佳性能。
const a = [91,65,91,88,26]
// return the max out of two numbers
const max = (x, y) => x > y ? x : y
const removeMax = a => {
// find the largest value in the array with reduce
const largest = a.reduce(max, 0)
// get the first index of the largest number
const index = a.indexOf(largest)
// return a new array without the largest number
return [
...a.slice(0, index),
...a.slice(index + 1)
]
}
console.log('before', a)
console.log('after', removeMax(a))
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>
pop
而不是delete
。 - JJJ