首页 文章资讯内容详情

在数组JavaScript中删除最小的数字

2026-06-05 1 花语

我们需要编写一个包含数字数组的JavaScript函数。该数字应在数组中找到最小的元素并将其删除。

为此的代码将是-

const arr = [2, 1, 3, 2, 4, 5, 1]; const removeSmallest = arr => { const smallestCreds = arr.reduce((acc, val, index) => { let { num, ind } = acc; if(val >= num){ return acc; }; ind = index; num = val; return { ind, num }; }, { num: Infinity, ind: -1 }); const { ind } = smallestCreds; if(ind === -1){ return; }; arr.splice(ind, 1); }; removeSmallest(arr); console.log(arr);

以下是控制台上的输出-

[ 2, 3, 2, 4, 5, 1 ]