使用splice()JavaScript更改数组
我们需要编写一个函数,给定一个数组arr和一个数字n,该函数返回元素重复次数不超过n次的数组。而且我们必须做到所有这些,而不会干扰所需元素的索引。因此,让我们为该函数编写代码,
我们将所有元素的计数保留在哈希映射中,并且在迭代期间,只要任何元素的计数超过最大计数,我们都将拼接该元素。为此的代码将是-
示例
const arr = [7, 26, 21, 41, 43, 2, 26, 24, 10, 26, 10, 10, 24, 35, 35, 35, 43, 26, 41, 7, 24, 24, 21, 24, 10, 35, 10, 7, 24, 7, 35, 26, 41, 35, 2, 43, 24, 2, 41, 26, 41, 7, 7, 26, 2, 10, 43, 10, 35, 41, 24, 7, 2, 2, 7, 2, 26, 24, 26, 43, 43, 21, 10, 28, 10]; const array = [12, 4, 2, 12, 32, 21, 67, 4, 32, 5]; const deleteExtra = (arr, n) => { const map = {}; for(let i = 0; i < arr.length; i++){ if(map[arr[i]]){ if(map[arr[i]] >= n){ arr.splice(i, 1); i--; }else{ map[arr[i]]++; } continue; }; map[arr[i]] = 1; } }; deleteExtra(array, 1); deleteExtra(arr, 2); console.log(array); console.log(arr);
输出结果
控制台中的输出将为-
[ 12, 4, 2, 32, 21, 67, 5 ] [ 7, 26, 21, 41, 43, 2, 26, 24, 10, 10, 24, 35, 35, 43, 41, 7, 21, 2, 28 ]