【问题标题】:Javascript reduce to a desire array using reduce and accJavascript 使用 reduce 和 acc 减少到期望数组
【发布时间】:2020-10-24 17:41:51
【问题描述】:

我有一个列表数组

const List = [
{id:1, name:"jack", sex:"male", age:23},
{id:2, name:"marry", sex:"female", age:18},
{id:3, name:"paul", sex:"male", age:12},
{id:4, name:"katty", sex:"female", age:20}
]

我想将数组减少到只有 [23,18,12,20]

我尝试使用reduce和accumulative

const newList = List.reduce(
 (acc, {age}) =>{
  acc = age 
  return acc
  },[]}

那么结果只显示最后一个年龄根本没有累积,不知道最好的方法是什么。

【问题讨论】:

  • 使用 map() 会更简单...newList = List.map(({age}) => age)
  • 你实际上可以使用Array.prototype.map来做到这一点。

标签: javascript arrays reduce accumulate


【解决方案1】:

只需在List.reduce中添加 .push(age)

const List = [
{id:1, name:"jack", sex:"male", age:23},
{id:2, name:"marry", sex:"female", age:18},
{id:3, name:"paul", sex:"male", age:12},
{id:4, name:"katty", sex:"female", age:20}
];

 let myNewData = new Array();
 const newList = List.reduce(
 (acc, {age}) =>{
   myNewData.push(age);
  return myNewData;
  },{});
   
alert(newList);

【讨论】:

    【解决方案2】:

    虽然map()比较简单,但是如果你真的想用reduce你可以使用spread语法返回一个新数组或者返回acc.concat(age)

    const List = [
    {id:1, name:"jack", sex:"male", age:23},
    {id:2, name:"marry", sex:"female", age:18},
    {id:3, name:"paul", sex:"male", age:12},
    {id:4, name:"katty", sex:"female", age:20}
    ]
    const newList = List.reduce((acc, {age}) => [...acc, age], []);
    // OR
    const list2 = List.reduce((acc, {age}) => acc.concat(age), []);
       
    console.log(newList);
    console.log(list2);

    【讨论】:

      【解决方案3】:

      使用Array#push 将元素附加到数组中。 acc = age 每次只重置累加器。

      const List = [
      {id:1, name:"jack", sex:"male", age:23},
      {id:2, name:"marry", sex:"female", age:18},
      {id:3, name:"paul", sex:"male", age:12},
      {id:4, name:"katty", sex:"female", age:20}
      ]
      const newList = List.reduce(
       (acc, {age}) =>{
        acc.push(age)
        return acc
        },[]);
      console.log(newList);

      这也可以更简单地使用Array#map 来完成,它通过将数组的每个元素转换为元素所传递到的回调的返回值来创建一个新数组。

      const List = [
      {id:1, name:"jack", sex:"male", age:23},
      {id:2, name:"marry", sex:"female", age:18},
      {id:3, name:"paul", sex:"male", age:12},
      {id:4, name:"katty", sex:"female", age:20}
      ];
      const res = List.map(({age})=>age);
      console.log(res);

      【讨论】:

        【解决方案4】:

        你想要的是map而不是reduce

        const ages = List.map(item => item.age)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-06
          • 2020-12-07
          • 2016-01-19
          • 2021-03-26
          • 1970-01-01
          • 2022-11-09
          • 2023-02-24
          • 2023-03-09
          相关资源
          最近更新 更多