Tìm phần tử nhỏ nhất và xóa nó in-place bằng splice().
Mã thực hiện
const arr = [2,1,3,2,4,5,1];
const removeSmallest = arr => {
const smallestCreds = arr.reduce((acc, val, i) => {
let {num, ind} = acc;
if (val >= num) return acc;
ind = i; num = val;
return {ind, num};
}, {num: Infinity, ind: -1});
if (smallestCreds.ind === -1) return;
arr.splice(smallestCreds.ind, 1);
};
removeSmallest(arr);
console.log(arr);
Kết quả
[ 2, 3, 2, 4, 5, 1 ]
Chỉ xóa lần xuất hiện đầu tiên của số nhỏ nhất (1 tại index 1).