Skip to content

Instantly share code, notes, and snippets.

@sithumonline
Created February 19, 2022 11:45
Show Gist options
  • Select an option

  • Save sithumonline/8ce0473d08691dc3603d409e2f0f0834 to your computer and use it in GitHub Desktop.

Select an option

Save sithumonline/8ce0473d08691dc3603d409e2f0f0834 to your computer and use it in GitHub Desktop.
Push object which fulfilling conditions
// yarn add lodash
let _ = require("lodash");
let ob = [
{
name: "John",
age: 30,
},
{
name: "Mike",
age: 23,
},
{
name: "Jane",
age: 34,
},
{
name: "Mary",
age: 28,
},
{
name: "Mark",
age: 18,
},
{
name: "Jill",
age: 25,
},
{
name: "Jack",
age: 35,
},
{
name: "Jill",
age: 12,
},
{
name: "Jo",
age: 15,
},
];
let ageGroups = [
{
name: "10-20",
start: 10,
end: 20,
data: [],
},
{
name: "20-30",
start: 20,
end: 30,
data: [],
},
{
name: "30-40",
start: 30,
end: 40,
data: [],
},
];
_.forEach(ob, (item) => {
let ageGroup = _.find(ageGroups, (ageGroup) => {
return ageGroup.start <= item.age && ageGroup.end >= item.age;
});
ageGroup.data.push(item);
});
console.log(JSON.stringify(ageGroups, null, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment