3 回答

TA貢獻1831條經驗 獲得超4個贊
找到最小的,找到它的索引,過濾掉該索引中的項目:
function removeSmallest(arr) {
const smallest = Math.min(...arr);
const index = arr.indexOf(smallest);
return arr.filter((_, i) => i !== index);
}
const result = removeSmallest([2, 1, 5, -10, 4, -10, 2])
console.log(result)

TA貢獻1951條經驗 獲得超3個贊
使用indexOf()獲得的最小元素的索引。然后用于slice()獲取該索引之前和之后的所有內容,并將它們與concat()
const arr = [10, 3, 5, 8, 1, 2, 1, 6, 8];
const smallest = Math.min(...arr);
const smallestIndex = arr.indexOf(smallest);
const newArr = arr.slice(0, smallestIndex).concat(arr.slice(smallestIndex+1));
console.log(newArr);

TA貢獻1942條經驗 獲得超3個贊
function removeSmallest(numbers) {
let indexOfMin = numbers.indexOf(Math.min(...numbers));
return [...numbers.slice(0, indexOfMin), ...numbers.slice(indexOfMin + 1)];
}
添加回答
舉報