我们需要编写一个包含一组文字的JavaScript函数。我们的函数应该返回一个新数组,其中所有三元组都已过滤。
为此的代码将是-
const arr1 = [1,1,1,3,3,5]; const arr2 = [1,1,1,1,3,3,5]; const arr3 = [1,1,1,3,3,3]; const arr4 = [1,1,1,1,3,3,3,5,5,5,5,5,5,5,5,5,5,5,5,7,7]; const removeTriplets = arr => { const hashMap = arr => arr.reduce((acc, val) => { if(val in acc){ acc[val]++; }else{ acc[val] = 1; }; return acc; }, {}); let res = []; let obj = hashMap(arr); for(let key in obj){ for(let i = 0; i < obj[key] % 3; i++){ res.push(key) }; } return res; } console.log(removeTriplets(arr1)); console.log(removeTriplets(arr2)); console.log(removeTriplets(arr3)); console.log(removeTriplets(arr4));
控制台中的输出-
[ '3', '3', '5' ] [ '1', '3', '3', '5' ] [] [ '1', '7', '7' ]