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将元素追加到数组中。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,你可以使用 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);

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

最新更新