比较并添加一行代码?

ama*_*ars 2 javascript dictionary push

给定一个数组
[9,5,4,2,1,1,5,8,1,1]

有没有办法删除所有的1s 并x在最后添加等量的s。为了得到这个
[9,5,4,2,5,8,x,x,x,x]

我正在寻找一种方法来做到这一点。好奇这里是否有我可能缺少的技术,或者可能没有。

this在下面的例子中使用 显然是错误的。但是让您了解我正在尝试做什么。

let test = [9,5,4,2,1,1,5,8,1,1];

console.log(test.map(el => el !== 1 ?el :this.push('x'));
Run Code Online (Sandbox Code Playgroud)

Use*_*863 5

使用filter()fill()

let test = [9, 5, 4, 2, 1, 1, 5, 8, 1, 1];

let res = test.filter(el => el !== 1)

res = res.concat(Array(test.length - res.length).fill('x'))

console.log(res);
Run Code Online (Sandbox Code Playgroud)

使用 reduce()

let test = [9, 5, 4, 2, 1, 1, 5, 8, 1, 1];

let res = test.reduceRight((a, e) => e !== 1 ? [e, ...a] : [...a, 'x'], [])

console.log(res);
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,[`Array#reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight) 存在。 (2认同)