Combine data from an array of objects based on one of them - javascript

Having an array of objects like this:
[{"event_id":1,"person":"John"},
{"event_id":2,"person":"John"},
{"event_id":3,"person":"Mike"},
{"event_id":1,"person":"Mike"},
{"event_id":1,"person":"Anna"},
{"event_id":3,"person":"Anna"}]
the wanted result should combine them based on the event_id and show them in a table structure like this:
1 John, Mike, Ana
2 John
3 Mike, Anna
Each row represents an event and the rows contains the people who participated in that event.
I don't know how do to this in JavaScript. Any suggestions?

You can use reduce:
const data = [
{ event_id: 1, person: 'John' },
{ event_id: 2, person: 'John' },
{ event_id: 3, person: 'Mike' },
{ event_id: 1, person: 'Mike' },
{ event_id: 1, person: 'Anna' },
{ event_id: 3, person: 'Anna' },
];
const result = data.reduce(
(acc, val) => ({
...acc,
[val.event_id]: acc[val.event_id] ? [...acc[val.event_id], val.person] : [val.person],
}),
{},
);
console.log(result);

You can use a Map with .reduce() to first group your objects, where the event_id is the key in the map, and the value is an array of accumulated person values for the same event_id values. You can then use Array.from() to map each [key, value] entry to a string of HTML for the table rows and data. You can then add this string to your HTML like so:
const arr = [{"event_id":1,"person":"John"},
{"event_id":2,"person":"John"},
{"event_id":3,"person":"Mike"},
{"event_id":1,"person":"Mike"},
{"event_id":1,"person":"Anna"},
{"event_id":3,"person":"Anna"}];
const table = `
<table>
${Array.from(
arr.reduce((m, {event_id:id, person}) => m.set(id, [...(m.get(id) || []), person]), new Map),
([key, arr]) => `<tr><td>${key}</td><td>${arr.join(', ')}</td></tr>`
).join('')}
</table>
`;
document.body.innerHTML = table;

I recommend you to use Map data type.
Map is a collection of keyed data items, just like an Object. But the
main difference is that Map allows keys of any type.
First of all we iterate on Array of Objects, then we check if there is any event_id in Map we push Object.person to the value of event_id entry :
const listOfObjects = [
{ "event_id": 1, "person": "John" },
{ "event_id": 2, "person": "John" },
{ "event_id": 3, "person": "Mike" },
{ "event_id": 1, "person": "Mike" },
{ "event_id": 1, "person": "Anna" },
{ "event_id": 3, "person": "Anna" }];
let eventIdCollection = new Map();
listOfObjects.forEach(obj => {
if (eventIdCollection.has(obj.event_id)) {
let persons = eventIdCollection.get(obj.event_id);
persons.push(obj.person);
eventIdCollection.set(obj.event_id, persons);
}
else {
eventIdCollection.set(obj.event_id, [obj.person]);
}
});
the result is Map of event_id to Array of persons.

Related

How to convert object into array in Javascript

I have the below object obj(coming as a JSON response):
var obj = {
0: {
note: 'test1',
id: 24759045,
createTimeStamp: '2022-08-01T17:05:36.750Z',
},
1: {
note: 'test2',
id: 24759045,
createTimeStamp: '2022-08-01T17:05:51.755Z',
},
note: 'test1',
id: 24759045,
createTimeStamp: '2022-08-01T17:05:36.750Z',
};
I only want the objects with numbers("0" , "1" .. so on) to be pushed in an array.
Below is what I am trying to do:
let items = [];
for (var prop in obj) {
items.push(obj[prop]);
}
console.log(items);
// expected output:
[
{
note: 'test1',
id: 24759045,
createTimeStamp: '2022-08-01T17:05:36.750Z',
},
{
note: 'test2',
id: 24759045,
createTimeStamp: '2022-08-01T17:05:51.755Z',
},
]
Any pointers would be highly appreciated.
A few things to consider here.
Are the numeric keys ordered?
Does the order matter?
Are the numeric keys an index of the item in the array?
Are there any gaps in the numeric keys?
First solution, assuming that the numeric keys are the index in the array.
const items = Object.keys(obj).reduce((acc, key) => {
const index = parseInt(key);
if (Number.isNaN(index)) {
return acc;
}
acc[index] = obj[key];
return acc;
}, []);
Second solution, assuming that order matters, but that the numeric keys are not guaranteed to be contiguous.
const items = Object.keys(obj)
.filter((key) => Number.isNaN(parseInt(key)) === false)
.sort()
.map((key) => obj[key]);
Keep in mind that Object.keys does not guarantee that the keys are ordered alpha-numerically. So if order matters, then you have to sort them.
Third solution, if order doesn't matter.
const items = Object.keys(obj)
.filter((key) => Number.isNaN(parseInt(key)) === false)
.map((key) => obj[key]);
var result = [];
var obj = {
"0": {
"note": "test1",
"id": 24759045,
"createTimeStamp": "2022-08-01T17:05:36.750Z"
},
"1": {
"note": "test2",
"id": 24759045,
"createTimeStamp": "2022-08-01T17:05:51.755Z"
},
"note": "test1",
"id": 24759045,
"createTimeStamp": "2022-08-01T17:05:36.750Z"
}
for (var i in obj)
result.push(obj[i]);
$('#result').html(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="result"></div>
You can achieve this by doing the following steps.
Copied your object below -->
var obj = {
"0": {
"note": "test1",
"id": 24759045,
"createTimeStamp": "2022-08-01T17:05:36.750Z"
},
"1": {
"note": "test2",
"id": 24759045,
"createTimeStamp": "2022-08-01T17:05:51.755Z"
},
"note": "test1",
"id": 24759045,
"createTimeStamp": "2022-08-01T17:05:36.750Z"
}
Created new js array -->
var result = [];
Code -->
for (var i in obj)
result.push(obj[i]);
Find the solution from link below as well --> :) :)
https://jsfiddle.net/kavinduxo/95qnpaed/
I think you'll need to get the keys of the object, filter out the non-numeric ones, then map each key to the obj[key]:
var obj={"0":{"note":"test1","id":24759045,
"createTimeStamp":"2022-08-01T17:05:36.750Z"},"1":{"note":"test2","id":24759045,
"createTimeStamp":"2022-08-01T17:05:51.755Z"},
"note":"test1","id":24759045,"createTimeStamp":"2022-08-01T17:05:36.750Z"};
console.log(
Object.keys(obj)
.filter((key) =>!Number.isNaN(parseInt(key)))
.map((key) => obj[key])
)

How to filter array of objects with nested objects with specific properties?

I am trying to filter a Javascript array of objects with nested objects with specific properties. I can filter the name, slug, website, launch year without any issues. But, I can not filter the category name (category.name) which is an object within the object. Why is filtering the category name not working?
var search = "qui"; // does not work (category.name)
// var search = "Sauer"; // works (name)
var data = [{ "name": "Sauer-Metz", "slug": "ab-laborum",
"website": "https://test.com", "launch_year": 2017, "category_id": 6,
"category": { "id": 6, "name": "qui", "slug": "qui" } } ];
var results = data.filter(company => [
'name', 'launch_year', 'website', 'category.name'
].some(key => String(company[key]).toLowerCase().includes(search.toLowerCase())));
console.log(results);
One way you can go about it is to have a value extractor like the one getKey below
const getKey = (value, key) => {
return key.split('.').reduce((acc, curr) => value[curr], '');
}
var results = data.filter(company => [
'name', 'launch_year', 'website', 'category.name'
].some(key => String(getKey(company, key)).toLowerCase().includes(search.toLowerCase())));
I believe you have to do a separate condition for this specific nested property, although there might be a cleaner way I don't see right now:
var results = data.filter(
(company) =>
["name", "launch_year", "website"].some((key) =>
String(company[key]).toLowerCase().includes(search.toLowerCase())
) ||
String(company["category"]["name"])
.toLowerCase()
.includes(search.toLowerCase())
);
Dot notation doesn't work like that.
const testCase1 = 'qui';
const testCase2 = 'Sauer';
const data = [
{
name: 'Sauer-Metz',
slug: 'ab-laborum',
website: 'https://test.com',
launch_year: 2017,
category_id: 6,
category: { id: 6, name: 'qui', slug: 'qui' },
},
];
const searchResults = (data, search) => {
return data.filter((item) => {
return (
item?.category?.name.toLowerCase().includes(search.toLowerCase()) ||
['name', 'launch_year', 'website'].some((key) => `${item[key]}`.toLowerCase().includes(search.toLowerCase()))
);
});
};
console.log('**CASE 1**')
console.log(searchResults(data, testCase1));
console.log('**CASE 2**')
console.log(searchResults(data, testCase2));
To use your approach you can convert 'category.name' to ['category','name'] and then use String(company[key[0]][key[1]])... whenever key is an array.
const search = "qui"; // does not work (category.name)
//const search = "Sauer"; // works (name)
const data = [{ "name": "Sauer-Metz", "slug": "ab-laborum", "website": "https://test.com", "launch_year": 2017, "category_id": 6, "category": { "id": 6, "name": "qui", "slug": "qui" } } ];
const results = data.filter(
company => [
'name', 'launch_year', 'website', ['category','name']
].some(
key =>
Array.isArray(key) ?
String(company[key[0]][key[1]]).toLowerCase().includes(search.toLowerCase()) :
String(company[key]).toLowerCase().includes(search.toLowerCase())
)
);
console.log(results);

How to map or assign an entry to an array-item based on some of this item's conditions?

I have array of objects,
if the name is xx then push xitems to that object and
if the name is yy then push yitems to that object
Below is the code tried , and also should not use spread operator
const result = [];
var ss=arrobj.forEach(function(e){
if(e.name === 'xx'){
result.push({id: e.id, name: e.name, country:e.country, others: xitems})
}
if(e.name === 'yy'){
result.push({id: e.id, name: e.name, country:e.country, others: yitems})
}
return result;
});
var arrobj =[
{id:1, name: "xx", country: "IN"},
{id:2, name: "yy", country: "MY"},
]
xitems =[
{title: "Finance", valid: true}
]
yitems =[
{title: "Sales", valid: true}
]
Expected Output
[
{id:1, name: "xx", country: "IN",
others:[
{title: "Finance", valid: true}
]
},
{id:2, name: "yy", country: "MY",
others: [
{title: "Sales", valid: true}
]
},
]
You should use .map for this.
const arrobj = [
{ id: 1, name: "xx", country: "IN" },
{ id: 2, name: "yy", country: "MY" },
];
const xitems = [{ title: "Finance", valid: true }];
const yitems = [{ title: "Sales", valid: true }];
const result = arrobj.map((item) => {
if (item.name === "xx") {
item.others = xitems;
} else if (item.name === "yy") {
item.others = yitems;
}
return item;
});
console.log(result);
Your code works, the only issue that I identified are.
There is no need to assign var ss with arrobj.forEach. Because Array.forEach donot return a value.
No need of return result; inside Array.forEach.
Also as an improvement you can simply assign the object with key others like Object.assign({}, e, { others: xitems }), rather than returning individual key value.
Working Fiddle
const arrobj = [
{ id: 1, name: "xx", country: "IN" },
{ id: 2, name: "yy", country: "MY" },
]
const xitems = [
{ title: "Finance", valid: true }
]
const yitems = [
{ title: "Sales", valid: true }
]
const result = [];
arrobj.forEach(function (e) {
if (e.name === 'xx') {
result.push(Object.assign({}, e, { others: xitems }))
}
if (e.name === 'yy') {
result.push(Object.assign({}, e, { others: yitems }))
}
});
console.log(result)
Variables are references to an object that has a value, variables do not store values. It is pointless to try to use a variable in that manner unless you have specific parameters. If you insist on a condition then you need to identify xitems and yitems by the objects values and/or properties or by the order they came in. If you have dynamic data how would you know what xitems or yitems really is?
The example below has been made reusable as long as you meet these requirements:
Must have an array of objects as a primary parameter.
Must have at least one array of objects for each object in the primary array. If there's more the rest will be ignored.
The secondary array of objects must be in the order you want then to end up as.
The second parameter is a rest parameter (not a spread operator, although I have no idea why OP does not want to use it). This will allow us to stuff in as many object arrays as we want.
const distOther = (main, ...oAs) => {...
Next we create an array of pairs from all of the secondary arrays
let others = oAs.map(sub => ['others', sub]);
// [['others', [{...}]], [['others', [{...}]], ...]
Then we turn our attention to the primary array. We'll work our way from the inside out. .map() each object as an array of pairs by Object.entries():
main.map((obj, idx) =>
// ...
Object.entries(obj)
// ...
// [{A: 1, B: 2}, {...}] => [[['A', 1], ['B', 2]], [[...], [...]]]
Then .concat() (a spead operator would be more succinct) each array of pairs with that of the secondary array of pairs corresponding to the current index (you'll need to wrap each secondary array in another array, so the return will level off correctly):
// main.map((obj, idx) =>
// ...
// Object.entries(obj)
.concat([others[idx]])));
// [[['A', 1], ['B', 2], ['others', [{...}]], [[...], [...], ['others', [{...}]]]
Finally we'll use Object.fromEntries() to convert each array of pairs into an object.
// main.map((obj, idx) =>
Object.fromEntries(
// Object.entries(obj)
// .concat([others[idx]])));
// [{'A': 1, 'B': 2, 'others': [{...}]},...]
const objArr =[
{id:1, name: "xx", country: "IN"},
{id:2, name: "yy", country: "MY"},
];
const x =[
{title: "Finance", valid: true}
]
const y =[
{title: "Sales", valid: true}
]
const distOther = (main, ...oAs) => {
let others = oAs.map(sub => ['others', sub]);
return main.map((obj, idx) =>
Object.fromEntries(
Object.entries(obj)
.concat([others[idx]])));
};
console.log(distOther(objArr, x, y));
I would choose a map based approach as well but without the if clauses which explicitly check for expected values of the mapped item's name property.
The approach instead utilizes map's 2nd thisArg parameter which gets applied as the mapper functions this context. Such an additional object can be provided as a map/index of custom key value pairs where key equals a mapped item's name.
Thus the mapper implementation features generic code, and due to the this binding it will be provided as function statement which makes it also re-usable and, if properly named, readable / comprehensible / maintainable too.
function assignBoundNamedValueAsOthers(item) {
// the bound key value pairs.
const index = this;
// create new object and assign, according to
// `item.name`, bound named value as `others`.
return Object.assign(
{},
item,
{ others: index[item.name] ?? [] },
);
}
const arrobj = [
{ id: 1, name: "xx", country: "IN" },
{ id: 2, name: "yy", country: "MY" },
];
const xitems = [{ title: "Finance", valid: true }];
const yitems = [{ title: "Sales", valid: true }];
const result = arrobj
.map(assignBoundNamedValueAsOthers, {
// each `key` equals an expected item's `name`.
xx: xitems,
yy: yitems,
});
console.log({
result,
arrobj,
xitems,
yitems,
});
.as-console-wrapper { min-height: 100%!important; top: 0; }
As one can see, the above implementation via Object.assign creates a new object from each mapped arrobj item. Thus the original item-references remains untouched / non mutated. It does not apply for the items of xitems and yitems since both array references are directly assigned each to its newly created others property. The above log does reflect this.
In case the goal was an entirely reference free data structure one needs to slightly change the Object.assign part of assignBoundNamedValueAsOthers ...
function assignBoundNamedValueAsOthers(item) {
// the bound key value pairs.
const index = this;
// create new object and assign, according to
// `item.name`, bound named value as `others`.
return Object.assign(
{},
item, {
others: (index[item.name] ?? [])
// dereference the `others` items as well.
.map(othersItem =>
Object.assign({}, othersItem)
)
},
);
}
const arrobj = [
{ id: 1, name: "xx", country: "IN" },
{ id: 2, name: "yy", country: "MY" },
];
const xitems = [{ title: "Finance", valid: true }];
const yitems = [{ title: "Sales", valid: true }];
const result = arrobj
.map(assignBoundNamedValueAsOthers, {
// each `key` equals an expected item's `name`.
xx: xitems,
yy: yitems,
});
console.log({
result,
arrobj,
xitems,
yitems,
});
.as-console-wrapper { min-height: 100%!important; top: 0; }
In case the OP does not need to care about immutability, the entire process then changes from a map task to a forEach task, where assignBoundNamedValueAsOthers does directly change/mutate each currently processed item of arrobj, thus forEach does not return any data but always the undefined value ...
function assignBoundNamedValueAsOthers(item) {
// the bound key value pairs.
const index = this;
// mutate the original reference of the currently
// processed `item` by directly assigning, according
// to `item.name`, the bound named value as `others`.
Object.assign(
item,
{ others: index[item.name] ?? [] },
);
// no explicit return value due to
// going to be used as a `forEach` task.
}
const arrobj = [
{ id: 1, name: "xx", country: "IN" },
{ id: 2, name: "yy", country: "MY" },
];
const xitems = [{ title: "Finance", valid: true }];
const yitems = [{ title: "Sales", valid: true }];
// mutates each item of `arrobj`.
arrobj.forEach(assignBoundNamedValueAsOthers, {
// each `key` equals an expected item's `name`.
xx: xitems,
yy: yitems,
});
console.log({
arrobj,
xitems,
yitems,
});
.as-console-wrapper { min-height: 100%!important; top: 0; }

Create Multidimensional array of [key,value] with key unique count as value from Array of JSON Object

Currently i have array of json object returned by server
data: [
{
billed: "No",
designation: "ASE",
involvement: "Full Time",
name: "Rishi Ranabhat",
project: "ABC"
},
{
billed: "No",
designation: "ASE",
involvement: "Full Time",
name: "Biplap Bhattarai",
project: "DEF"
},
{
billed: "No",
designation: "SE",
involvement: "Part Time",
name: "Ram k",
project: "DEF"
},
...more json data
];
I have to create a count of values in Array like below for representation for google charts:
[
//designation count
["ASE", 2],
["SE", 2]
],
[
//project count
["ABC", 1],
["DEF", 2]
],
//and similarly others.
How can i count the no of occurances of the keys with the values of previous occurance intact,
and also in ['key','value'] of key being the unique occurance of data and value being the no of occurance ???
Iterate over the data with reduce to create an object grouped by type. Here's a reusable function - just pass in the data and the type.
const data = [{"billed":"No","designation":"ASE","involvement":"Full Time","name":"Rishi Ranabhat","project":"ABC"},{"billed":"No","designation":"ASE","involvement":"Full Time","name":"Biplap Bhattarai","project":"DEF"},{"billed":"No","designation":"SE","involvement":"Part Time","name":"Ram k","project":"DEF"}];
function getCount(data, type) {
// `map` out the data by type
const typeArr = data.map((obj) => obj[type]);
// Iterate over the type data. We pass in an initial
// object to capture the counts, so we need to use
// `Object.values` to grab the object values at the end
// of the iteration
return Object.values(typeArr.reduce((acc, id) => {
// If the key doesn't exist in the accumulator object
// create it and create a new array at its value
acc[id] = acc[id] || [id, 0];
// Increment the second index (the count)
acc[id][1]++;
// Return the object for the next iteration
return acc;
}, {}));
}
console.log(getCount(data, 'designation'));
console.log(getCount(data, 'project'));
Further reading
reduce
Object.values
Alternatively, if you wanted to do this in one operation and return an object containing the grouped information, you could use another reduce to iterate over the main data keys:
const data = [{"billed":"No","designation":"ASE","involvement":"Full Time","name":"Rishi Ranabhat","project":"ABC"},{"billed":"No","designation":"ASE","involvement":"Full Time","name":"Biplap Bhattarai","project":"DEF"},{"billed":"No","designation":"SE","involvement":"Part Time","name":"Ram k","project":"DEF"}];
function getCounts(data) {
// Grab the data keys. It assumes that each object in
// the array has the same keys
const keys = Object.keys(data[0]);
// Using `reduce` iterate over the keys to build
// up an object that groups the results from the inner
// `reduce` operation by key
return keys.reduce((out, key) => {
// `map` out the data by type
const typeArr = data.map((obj) => obj[key]);
// Iterate over the type data. We pass in an initial
// object to capture the counts, so we need to use
// `Object.values` to grab the object values at the end
// of the iteration
out[key] = Object.values(typeArr.reduce((acc, id) => {
// If the key doesn't exist in the accumulator object
// create it and create a new array at its value
acc[id] = acc[id] || [id, 0];
// Increment the second index (the count)
acc[id][1]++;
// Return the object for the next iteration
return acc;
}, {}));
// Return the `out` object for the next iteration
return out;
}, {});
}
console.log(getCounts(data));
Lot's of ways to do this. Here is a simple way (could be cleaned up, but just trying to demo):
View on JSFiddle
const data = [{
billed: "No",
designation: "ASE",
involvement: "Full Time",
name: "Rishi Ranabhat",
project: "ABC"
},
{
billed: "No",
designation: "ASE",
involvement: "Full Time",
name: "Biplap Bhattarai",
project: "DEF"
},
{
billed: "No",
designation: "SE",
involvement: "Part Time",
name: "Ram k",
project: "DEF"
}
];
const designations = [],
projects = [];
for (const record of data) {
// Count designations
if (!designations[record.designation]) {
designations[record.designation] = 0;
}
designations[record.designation] = designations[record.designation] + 1;
// Count projects
if (!projects[record.project]) {
projects[record.project] = 0;
}
projects[record.project] = projects[record.project] + 1;
}
// Merge sets
const final = [designations, projects];
console.log(final);
const data = [
{
billed: "No",
designation: "ASE",
involvement: "Full Time",
name: "Rishi Ranabhat",
project: "ABC"
},
{
billed: "No",
designation: "ASE",
involvement: "Full Time",
name: "Biplap Bhattarai",
project: "DEF"
},
{
billed: "No",
designation: "SE",
involvement: "Part Time",
name: "Ram k",
project: "DEF"
}
];
const result = data.reduce((acc,cur) => {
for(let k in cur) {
if(!acc[k]) {
acc[k] = [[cur[k], 1]];
} else {
const idx = acc[k].findIndex(e => e[0] === cur[k]);
if(idx !== -1) {
acc[k][idx][1]++
} else {
acc[k].push([cur[k], 1])
}
}
}
return acc;
}, {});
console.log(result)

How do I transform an array to hold data based on a value in the data?

I have seen some questions that might look similar but none is the solution in my case. I want to regroup and recreate my array the way that it is arranged or grouped based on one of my values(age). I want to have all data of the same "age" in one place. So here is my sample array:
[
{
"age": 15,
"person": {
name: 'John',
hobby: 'ski'
},
},
{
"age": 23,
"person": {
name: 'Suzi',
hobby: 'golf'
},
},
{
"age": 23,
"person": {
name: 'Joe',
hobby: 'books'
}
},{
"age": 25,
"person": {
name: 'Rosi',
hobby: 'books'
}
},{
"age": 15,
"person": {
name: 'Gary',
hobby: 'books'
}
},
{
"age": 23,
"person": {
name: 'Kane',
hobby: 'books'
}
}
]
And I need to have an array that kind of have age as a key and person as value, so each key could have multiple values meaning the value will kind of be an array itself.
I have read this and this questions and many more but they were not exactly the same.
I feel like I need to use reduce to count duplicate ages and then filter it based on that but how do I get the values of those ages?
EIDT:
Sorry for not being clear:
This is what I need:
{
23: [
{ name: 'Suzi', hoby: 'golf' },
{ name: 'Joe', hobby: 'books'}
],
15: [
{ name: 'Gary', hobby: 'books' }
] ,
.
.
.
}
You're actually going to want to reduce, not filter. Filtering an Array means to remove elements and place the kept elements into a new container. Reducing an array means to transform it into a single value in a new container. Mapping an array means to transform every value in place to a new container. Since you want to change how the data is represented that's a Reduction, from one form to another more condensed form.
Assume your Array of values is stored in let people = [...]
let peopleByAge = people.reduce(function (accumulator, value, index, array){
// The first time through accumulator is the passed extra Object after this function
// See the MDN for Array.prototype.reduce() for more information
if (accumulator[value.age] == undefined){
accumulator[value.age] = [];
}
accumulator[value.age].push(value);
return accumulator
}, {})
console.log(peopleByAge) // { 23: [{ age: 23, name: ..., hobby: ...}, ...], 13: [...], ...}
You can find the MDN article for Array#reduce() here
Thanks to #RobertMennell who patiently answered me and I voted as answer. But I just wanted to write my version which MDN had a great example of. It is a longer version assuming the people is the array name:
const groupedByvalue = 'age';
const groupedArray = people;
const groupBy = (peopleArray, value) => {
return peopleArray.reduce((acc, obj) => {
const key = obj[value];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
console.log(groupBy(groupedArray,groupedByvalue));
Update:
More polished using ternary operator:
const groupedByvalue = 'age';
const groupedArray = people;
const groupBy = (peopleArray, value) => {
return peopleArray.reduce((acc, obj) => {
const key = obj[value];
(!acc[key]) ? (acc[key] = []) : (acc[key].push(obj))
return acc;
}, {});
}
console.log(groupBy(groupedArray,groupedByvalue));

Categories

Resources