I may use the implicit variables so that you could read easily, see my comments for the explanations
// get the input property to group by, we attach the function to the prototype objectArray.prototype.groupBy=function(prop){// then apply reducereturnthis.reduce((group,item)=>{// create new property for the group object if not existed, if yes, reassign from the accumulator group[item[prop]]=group[item[prop]]||[];// add new item to the group of property (in this case, a list) we want to groupgroup[item[prop]].push(item);returngroup;// create initial empty object to implement reduce},{});};
Then we can use people.groupBy('gender') or people.groupBy('age')
people.reduce(...)
answer is a masterpiece 👏🏻Masterpiece.
Using .filter for the second task
A more generic solution to group by any property:
Didn't understand It can you explain a little more.
I may use the implicit variables so that you could read easily, see my comments for the explanations
Then we can use
people.groupBy('gender')
orpeople.groupBy('age')
people = [
// { name: 'Alice', age: 21, gender: "female" },
// { name: 'Max', age: 20, gender: "male" },
// { name: 'Jane', age: 20, gender: "female" },
// { name: 'Jon', age: 21, gender: "male" },
// { name: 'Alex', age: 20, gender: "male" }
// ]
// const male=people.filter((el)=>el.gender=="male")
// const female=people.filter((el)=>el.gender=="female")
// console.log({male:male,female:female})
// let result = [{x: 1}, {x: 2}, {x: 3}];
// res=result.reduce((acc,el)=>acc+el.x,0)
let value = "5+8=x";
let arr=value.split("=")
arr=arr[0].split("+").map(Number).reduce((acc,e)=>acc+e)
console.log(arr)