繁体   English   中英

Javascript 使用 reduce 和 acc 减少到所需的数组

[英]Javascript reduce to a desire array using reduce and acc

我有一个列表数组

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]

我尝试使用减少和累积

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

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

你想要的是mapreduce

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

使用Array#push将 append 一个元素添加到数组中。 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);

虽然 map() 更简单,但如果你真的想使用 reduce,你可以使用扩展语法返回一个新数组或返回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);

只需在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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM