比较并添加一行代码?

问题描述 投票:1回答:4

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

有没有一种方法可以删除所有1,并在末尾添加等量的x。为了得到这个[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'));
javascript dictionary push
4个回答
1
投票

无法在一个操作/循环中完成(或至少容易完成),但可以在一行中完成:

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

let output = test.map((num) => num === 1 ? 'x' : num).sort((a,b) => b === 'x' ? -1 : 0)

console.log(output);

您对this的使用没有道理;在循环操作中,您可以return所需的输出(显式或隐式从胖箭头函数返回)。

因此,在上面的示例中,我们首先对.map使用循环一次,以返回一个新数组,该数组将所有.map替换为1。然后,我们将新返回的数组循环到"x" .sort的所有实例,直到该数组的末尾。


2
投票

使用.sort"1"

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);

1
投票

您可能需要两个循环才能使数组重新排序。

reduce()

基本上与let test = [9, 5, 4, 2, 1, 1, 5, 8, 1, 1]; let res = test.reverse().reduce((a, e) => e !== 1 ? [e, ...a] : [...a, 'x'], []) console.log(res);回调中的内容相同。

var array = [9, 5, 4, 2, 1, 1, 5, 8, 1, 1],
    j = 0;

console.log(...array);

for (let i = 0; i < array.length; i++) {
    if (array[i] !== 1) array[j++] = array[i];
}
while (j < array.length) array[j++] = 'x';

console.log(...array);

使用值映射的更短方法

forEach

0
投票

[使用var array = [9, 5, 4, 2, 1, 1, 5, 8, 1, 1]; array.forEach((j => (v, i, a) => { if (i + 1 === a.length) while (j < a.length) a[j++] = 'x'; else if (v !== 1) a[j++] = v; })(0)); console.log(...array);:您无法从var array = [9, 5, 4, 2, 1, 1, 5, 8, 1, 1]; array = array.map((j => (v, _, a) => { while (a[j] === 1) j++; return j in a ? a[j++] : 'x'; })(0)); console.log(...array);回调中访问this正在构建的数组,在map返回它之前,您的代码将无法访问它。

从技术上讲,您可以在一行上用一个表达式来执行此操作:

map

假定原始文档中没有map项,考虑到给出的样本,这似乎是合理的。

实时示例:

console.log(Array.from(Object.assign(test.filter(el => el !== 1), {length: test.length})).map(el => el === undefined ? "x" : el));
undefined

但是,我强烈建议不要这样做。我只是用简单的方式做:

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

console.log(Array.from(Object.assign(test.filter(el => el !== 1), {length: test.length})).map(el => el === undefined ? "x" : el));

实时示例:

.as-console-wrapper {
    max-height: 100% !important;
}
const result = test.filter(el => el !== 1);
while (result.length < test.length) {
    result.push("x");
}

或者也许

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

const result = test.filter(el => el !== 1);
while (result.length < test.length) {
    result.push("x");
}

console.log(result);

实时示例:

.as-console-wrapper {
    max-height: 100% !important;
}
const result = test.filter(el => el !== 1);
result.push(...Array(test.length - result.length).fill("x"));

...但是对我来说有点太复杂了。

© www.soinside.com 2019 - 2024. All rights reserved.