【问题标题】:abc.filter().map() ==> to reduce() How should I use it? JavaScriptabc.filter().map() ==> to reduce() 应该怎么用? JavaScript
【发布时间】:2019-03-12 12:54:51
【问题描述】:

有一个数组:

let x = [12,2,3.5,4,-29];
let squared = x.filter((a) => a>0 && Number.isInteger(a)).map((a) => a**2);

请问,如何使用 reduce() 来写这个?关键是——在给定的数组中获取平方数(仅限整数),大于“0”。有任何想法吗?谢谢。

【问题讨论】:

  • 你为什么想要reduce来写这个?既然你想创建一个结果数组,filtermap 是完全合适的。
  • 是的,filter)_ 和 map() 都是合适的。但是,使用 reduce()——我已经证明——一个脚本少用了 10 步。使用 filter() 和 map() 我应该通过一个数组两次。 Reduce() 只允许我一次。

标签: javascript dictionary filter reduce


【解决方案1】:

您可以使用conditional (ternary) operator ?: 并将平方值或空数组连接到累加器。

var x = [12, 2, 3.5, 4, -29],
    squared = x.reduce((r, a) => r.concat(a > 0 && Number.isInteger(a)
        ? a ** 2
        : []
    ), []);

console.log(squared);

或者,正如 Bergi 建议的那样,传播价值观。

var x = [12, 2, 3.5, 4, -29],
    squared = x.reduce((r, a) => a > 0 && Number.isInteger(a) ? [...r, a ** 2] : r , []);

console.log(squared);

【讨论】:

  • 我想你的意思是a ** 2
  • 哦,endlich das Licht am Ende des Tunnels, und das ist nicht ein Zug。丹克)
  • r.concat 有数字吗?这是适合传播语法的罕见情况之一:(r, a) => … ? [...r, a**2] : r
【解决方案2】:

原文:

let x = [12,2,3.5,4,-29];
let squared = x.filter((a) => a>0 && Number.isInteger(a)).map((a) => a**2);

现在,想想我们要在这里做什么才能使用 reduce 方法。

我们想要一个数组并返回一个由原始数组中所有正整数的平方组成的新数组。

这意味着我们在 reduce 中的累加器应该是一个数组,因为我们在最后返回一个数组。这也意味着我们需要包含逻辑控制流,以仅将正整数元素添加到累加器中。

示例如下:

const x = [12,2,3.5,4,-29];
const squared = x.reduce((acc, val) => val > 0 && val % 1 === 0 ? acc.concat(val ** 2) : acc, []);

console.log(squared);
// [144, 4, 16]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多