I have array list as follow:
let data =[
{
"id": "05a87dssff-7468-49b1-bae3-0cd06dc22189",
"details": [
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "chicken burger",
"price": 15,
"total": "60.00",
}
]
],
},
{
"id": "05a87dff-746gf-49b1-bae3-s0cd06dc22189",
"details": [
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "chicken burger",
"price": 15,
"total": "60.00",
}
]
],
},
{
"id": "06129f89-dd80-49dd-bf5d-a12764c23949",
"details": [
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "Beef burger",
"price": 15,
"total": "60.00",
}
],
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "Beef burger",
"price": 15,
"total": "60.00",
}
],
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "chicken burger",
"price": 15,
"total": "60.00",
}
]
],
}
]
I am trying to group all the arrays that have same name and then sum the values of the properties that have the same name in one grand total,
so the expected result based on the above array is:
[{'name':'chicken burger', 'total': 180},{'name':'Beef burger', 'total': 120}]
What i have tried is the following however, it keeps giving me the all array separated not grouped,
here is what i have done so far:
data.map(a => a.details.map(b => b.reduce((d,e)=> {
const newArr = d;
if (d.length && d[d.length - 1]['name'] === e['name'])
newArr[d.length - 1] =
{
//...d[d.length - 1], ...e,
total: parseFloat(d[d.length - 1].d) + parseFloat(e.total),
}
else newArr[d.length] = { ...e }
console.log(newArr)
return newArr;
},[]) ) );
and here a link to the code
Iterate over the array, using Map to store calculated sum.
let data =[ { "id": "05a87dssff-7468-49b1-bae3-0cd06dc22189", "details": [ [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "chicken burger", "price": 15, "total": "60.00", } ] ], }, { "id": "05a87dff-746gf-49b1-bae3-s0cd06dc22189", "details": [ [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "chicken burger", "price": 15, "total": "60.00", } ] ], }, { "id": "06129f89-dd80-49dd-bf5d-a12764c23949", "details": [ [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "Beef burger", "price": 15, "total": "60.00", } ], [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "Beef burger", "price": 15, "total": "60.00", } ], [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "chicken burger", "price": 15, "total": "60.00", } ] ] }];
const map = new Map();
data.forEach(
item => item.details.forEach(
detail => {
const {name, total} = detail[0];
map.has(name) ? map.get(name).total += +total : map.set(name, {name, total: +total})
}
)
);
const result = [...map.values()];
console.log(result);
You can use Array.prototype.map() to get the names and totals from the all the details arrays.
Then, use Array.prototype.reduce() in order to group the names.
let data = [
{
"id": "05a87dssff-7468-49b1-bae3-0cd06dc22189",
"details": [
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "chicken burger",
"price": 15,
"total": "60.00",
}
]
],
},
{
"id": "05a87dff-746gf-49b1-bae3-s0cd06dc22189",
"details": [
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "chicken burger",
"price": 15,
"total": "60.00",
}
]
],
},
{
"id": "06129f89-dd80-49dd-bf5d-a12764c23949",
"details": [
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "Beef burger",
"price": 15,
"total": "60.00",
}
],
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "Beef burger",
"price": 15,
"total": "60.00",
}
],
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "chicken burger",
"price": 15,
"total": "60.00",
}
]
],
}
]
const namesAndTotals = data.flatMap(item => item.details.flat().map(({ name, total }) => ({ name, total: Number(total) })));
const res = Object.values(namesAndTotals.reduce((acc, { name, total }) => {
if(!acc[name]) {
acc[name] = {
name,
total
}
} else {
acc[name].total += total;
}
return acc;
}, {}));
console.log(res);
Related
Currently have an array of objects which contain game releases. However game releases can happen on multiple platforms and these appear as separate objects within the array. I'm looking to remove duplicate games by comparing the game id but merge the platforms object
I have tried using the reduce function which successfully removes duplicate objects by game id but I'm unable to adapt this to merge platforms
const filteredArr = data.reduce((acc, current) => {
const x = acc.find(item => item.game.id === current.game.id);
if (!x) {
return acc.concat([current]);
} else {
return acc;
}
}, []);
Current Array:
const data = [{
"id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": {"id": 48, "name": "PlayStation 4"},
"region": 8,
"y": 2019
}, {
"id": 12,
"date": 1553212800,
"game": {
"id": 76832,
"name": "Spiderman",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": {"id": 6, "name": "PC (Microsoft Windows)"},
"region": 8,
"y": 2019
}, {
"id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": {"id": 48, "name": "Xbox"},
"region": 8,
"y": 2019
}]
Expected format after merge:
[{
"id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platforms": ["PlayStation", "Xbox"],
"region": 8,
"y": 2019
}, {
"id": 12,
"date": 1553212800,
"game": {
"id": 76832,
"name": "Spiderman",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platforms": ["Playstation"],
"region": 8,
"y": 2019
}]
You were really close, you just need to change the logic a bit. You can try something like the following; an example - https://repl.it/#EQuimper/ScaryBumpyCircle
const filteredArr = data.reduce((acc, current) => {
const x = acc.find(item => item.game.id === current.game.id);
if (!x) {
current.platform = [current.platform]
acc.push(current);
} else {
x.platform.push(current.platform);
}
return acc;
}, []);
The return value is
[
{
"id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": [
{
"id": 48,
"name": "PlayStation 4"
},
{
"id": 48,
"name": "Xbox"
}
],
"region": 8,
"y": 2019
},
{
"id": 12,
"date": 1553212800,
"game": {
"id": 76832,
"name": "Spiderman",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": [
{
"id": 6,
"name": "PC (Microsoft Windows)"
}
],
"region": 8,
"y": 2019
}
]
If you want to have just an array of platform strings, go with
const filteredArr = data.reduce((acc, current) => {
const x = acc.find(item => item.game.id === current.game.id);
if (!x) {
current.platform = [current.platform.name]
acc.push(current);
} else {
x.platform.push(current.platform.name);
}
return acc;
}, []);
And now the return value is
[
{
"id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": [
"PlayStation 4",
"Xbox"
],
"region": 8,
"y": 2019
},
{
"id": 12,
"date": 1553212800,
"game": {
"id": 76832,
"name": "Spiderman",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": [
"PC (Microsoft Windows)"
],
"region": 8,
"y": 2019
}
]
You could separate platform of the object and look if you have an object with the same id and add the platfor tho the array, of not create a new data set.
const
data = [{ id: 157283, date: 1553212800, game: { id: 76882, name: "Sekiro: Shadows Die Twice", popularity: 41.39190295640344 }, human: "2019-Mar-22", m: 3, platform: { id: 48, name: "PlayStation 4" }, region: 8, y: 2019 }, { id: 12, date: 1553212800, game: { id: 76832, name: "Spiderman", popularity: 41.39190295640344 }, human: "2019-Mar-22", m: 3, platform: { id: 6, name: "PC (Microsoft Windows)" }, region: 8, y: 2019 }, { id: 157283, date: 1553212800, game: { id: 76882, name: "Sekiro: Shadows Die Twice", popularity: 41.39190295640344 }, human: "2019-Mar-22", m: 3, platform: { id: 48, name: "Xbox" }, region: 8, y: 2019 }],
result = data.reduce((r, { platform, ...o }) => {
var temp = r.find(({ id }) => id === o.id);
if (!temp) r.push(temp = { ...o, platforms: [] });
temp.platforms.push(platform);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Please take a look:
const data = [ { "id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": {
"id": 48,
"name": "PlayStation 4"
},
"region": 8,
"y": 2019
},
{
"id": 12,
"date": 1553212800,
"game": {
"id": 76832,
"name": "Spiderman",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": {
"id": 6,
"name": "PC (Microsoft Windows)"
},
"region": 8,
"y": 2019
},{ "id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": {
"id": 48,
"name": "Xbox"
},
"region": 8,
"y": 2019
},
]
const filteredArr = data.reduce((acc, current) => {
const x = acc.find(item => item.game.id === current.game.id);
if (!x) {
current.platform = [current.platform.name]
return acc.concat([current]);
} else {
x.platform.push(current.platform.name);
return acc;
}
}, []);
console.log(filteredArr);
Here is another solution, using forEach instead of reduce. This makes use of a lookup hash that makes if faster for larger amounts of data then using find.
const data = [{"id": 157283, "date": 1553212800, "game": {"id": 76882, "name": "Sekiro: Shadows Die Twice", "popularity": 41.39190295640344}, "human": "2019-Mar-22", "m": 3, "platform": {"id": 48, "name": "PlayStation 4"}, "region": 8, "y": 2019}, {"id": 12, "date": 1553212800, "game": {"id": 76832, "name": "Spiderman", "popularity": 41.39190295640344}, "human": "2019-Mar-22", "m": 3, "platform": {"id": 6, "name": "PC (Microsoft Windows)"}, "region": 8, "y": 2019}, {"id": 157283, "date": 1553212800, "game": {"id": 76882, "name": "Sekiro: Shadows Die Twice", "popularity": 41.39190295640344}, "human": "2019-Mar-22", "m": 3, "platform": {"id": 48, "name": "Xbox"}, "region": 8, "y": 2019}];
let result = {};
data.forEach(({platform, ...release}) => {
release.platforms = [platform.name];
const releaseLookup = result[release.game.id];
if (!releaseLookup) {
result[release.game.id] = release;
} else {
releaseLookup.platforms.push(...release.platforms);
}
});
console.log(Object.values(result));
I am getting this type of json in my $scope of angularjs:
$scope.someStuff = {
"id": 2,
"service": "bike",
"min": "22",
"per": "100",
"tax": "1",
"categoryservices": [
{
"id": 32,
"category": {
"id": 1,
"name": "software"
}
},
{
"id": 33,
"category": {
"id": 2,
"name": "hardware"
}
},
{
"id": 34,
"category": {
"id": 3,
"name": "waterwash"
}
}
]
}
I want to use angularjs forEach loop and i want to get only category name,
My expected output:
[{"name":"software"}, {"name":"hardware"}, {"name":"waterwash"}]
You can use Array.map()
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
$scope.someStuff.categoryservices.map((x) => { return { name: x.category.name}})
var obj = {
"id": 2,
"service": "bike",
"min": "22",
"per": "100",
"tax": "1",
"categoryservices": [{
"id": 32,
"category": {
"id": 1,
"name": "software"
}
},
{
"id": 33,
"category": {
"id": 2,
"name": "hardware"
}
},
{
"id": 34,
"category": {
"id": 3,
"name": "waterwash"
}
}
]
};
console.log(obj.categoryservices.map((x) => {
return {
name: x.category.name
}
}))
You can use map method by passing a callback function as parameter.
const someStuff = { "id": 2, "service": "bike", "min": "22", "per": "100", "tax": "1", "categoryservices": [ { "id": 32, "category": { "id": 1, "name": "software" } }, { "id": 33, "category": { "id": 2, "name": "hardware" } }, { "id": 34, "category": { "id": 3, "name": "waterwash" } } ] }
let array = someStuff.categoryservices.map(function({category}){
return {'name' : category.name}
});
console.log(array);
root1
child1
child2
grandchild1
grandchild2
child3
root2
child1
child2
grandchild1
greatgrandchild1
I have an object array like tree structure like above, I want to get all unique paths in like this
Food->Dry Food Items->Local Dry Food Items
Food->Dry Food Items->Thai Dry Food Items
Food->Dry Food Items->Others
Food->Fruits
------
------
This is my object
[
{
"id": 1,
"name": "Food",
"parent_id": 0,
"children": [
{
"id": 5,
"name": "Dry Food Items",
"parent_id": 1,
"children": [
{
"id": 11,
"name": "Local Dry Food Items",
"parent_id": 5
},
{
"id": 12,
"name": "Thai Dry Food Items",
"parent_id": 5
},
{
"id": 60,
"name": "Others",
"parent_id": 5
}
]
},
{
"id": 6,
"name": "Fruits",
"parent_id": 1
},
{
"id": 7,
"name": "LG Branded",
"parent_id": 1
},
{
"id": 8,
"name": "Meat",
"parent_id": 1
},
{
"id": 9,
"name": "Sea food",
"parent_id": 1
},
{
"id": 10,
"name": "Vegetables",
"parent_id": 1,
"children": [
{
"id": 14,
"name": "Local Vegetables",
"parent_id": 10
},
{
"id": 15,
"name": "Thai Vegetables",
"parent_id": 10
}
]
},
{
"id": 38,
"name": "Frozen",
"parent_id": 1
},
{
"id": 39,
"name": "IP Kitchen",
"parent_id": 1,
"children": [
{
"id": 40,
"name": "IP Meat",
"parent_id": 39
},
{
"id": 41,
"name": "IP Starter",
"parent_id": 39
},
{
"id": 42,
"name": "IP Ingredients",
"parent_id": 39
},
{
"id": 43,
"name": "IP Sauce",
"parent_id": 39
},
{
"id": 44,
"name": "IP Seafood",
"parent_id": 39
},
{
"id": 45,
"name": "IP Starter",
"parent_id": 39
},
{
"id": 46,
"name": "IP Desert",
"parent_id": 39
}
]
}
]
},
{
"id": 2,
"name": "Beverage",
"parent_id": 0,
"children": [
{
"id": 16,
"name": "Bar",
"parent_id": 2
},
{
"id": 17,
"name": "Coffee & Tea",
"parent_id": 2
},
{
"id": 18,
"name": "In Can",
"parent_id": 2
},
{
"id": 19,
"name": "Water",
"parent_id": 2
},
{
"id": 47,
"name": "IP Bar",
"parent_id": 2
}
]
},
{
"id": 3,
"name": "Disposable",
"parent_id": 0,
"children": [
{
"id": 21,
"name": "Disposable",
"parent_id": 3
}
]
},
{
"id": 4,
"name": "SOE",
"parent_id": 0,
"children": [
{
"id": 20,
"name": "Cleaning Materials",
"parent_id": 4
},
{
"id": 22,
"name": "Chinaware",
"parent_id": 4
}
]
}
];
I get to all the nodes in the tree
function traverse(categories) {
categories.forEach(function (category) {
if (category.children && category.children.length) {
traverse(category.children);
}
else {
}
}, this);
}
You can use recursion and create a function using forEach loop.
var arr = [{"id":1,"name":"Food","parent_id":0,"children":[{"id":5,"name":"Dry Food Items","parent_id":1,"children":[{"id":11,"name":"Local Dry Food Items","parent_id":5},{"id":12,"name":"Thai Dry Food Items","parent_id":5},{"id":60,"name":"Others","parent_id":5}]},{"id":6,"name":"Fruits","parent_id":1},{"id":7,"name":"LG Branded","parent_id":1},{"id":8,"name":"Meat","parent_id":1},{"id":9,"name":"Sea food","parent_id":1},{"id":10,"name":"Vegetables","parent_id":1,"children":[{"id":14,"name":"Local Vegetables","parent_id":10},{"id":15,"name":"Thai Vegetables","parent_id":10}]},{"id":38,"name":"Frozen","parent_id":1},{"id":39,"name":"IP Kitchen","parent_id":1,"children":[{"id":40,"name":"IP Meat","parent_id":39},{"id":41,"name":"IP Starter","parent_id":39},{"id":42,"name":"IP Ingredients","parent_id":39},{"id":43,"name":"IP Sauce","parent_id":39},{"id":44,"name":"IP Seafood","parent_id":39},{"id":45,"name":"IP Starter","parent_id":39},{"id":46,"name":"IP Desert","parent_id":39}]}]},{"id":2,"name":"Beverage","parent_id":0,"children":[{"id":16,"name":"Bar","parent_id":2},{"id":17,"name":"Coffee & Tea","parent_id":2},{"id":18,"name":"In Can","parent_id":2},{"id":19,"name":"Water","parent_id":2},{"id":47,"name":"IP Bar","parent_id":2}]},{"id":3,"name":"Disposable","parent_id":0,"children":[{"id":21,"name":"Disposable","parent_id":3}]},{"id":4,"name":"SOE","parent_id":0,"children":[{"id":20,"name":"Cleaning Materials","parent_id":4},{"id":22,"name":"Chinaware","parent_id":4}]}]
function getNames(data) {
var result = [];
function loop(data, c) {
data.forEach(function (e) {
var name = !c.length ? e.name : c + '->' + e.name;
if (e.children) { loop(e.children, name); }
else {
result.push({ name: name });
}
});
}
loop(data, '');
return result;
}
console.log(getNames(arr))
I have an Array with these values, I need to create a loop on these values to return in alasql like this example:
http://jsfiddle.net/agershun/11gd86nx/5/
var data = {
"business": [
{
"order_contents": [
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 85,
"name": "product 3",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 84,
"name": "product 2",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 84,
"name": "product 2",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
}
]
}
]
};
here's my code..
info.orderByChild("data").startAt("08/04/2017").endAt("12/06/2017").on('value', function(snapshot){
snapshot.forEach(function(item) {
jsonObj = {
"business": [
{
"order_contents": [
{
"id": itemVal['id'],
"name": itemVal['name'],
"price": itemVal['price'],
"quantity": itemVal['quantity'],
"total": "itemVal['total']
}
]
}
]
}
its not creating an array, only the last value..
can someone help me?
You have to define your array in the beginning and add each object to it later on in your loop:
var result = { business: [] }; // PLACEHOLDER
var jsonObj;
info.orderByChild("data").startAt("08/04/2017").endAt("12/06/2017").on('value', function(snapshot) {
snapshot.forEach(function(item) {
jsonObj = {
"order_contents": [
{
"id": itemVal['id'],
"name": itemVal['name'],
"price": itemVal['price'],
"quantity": itemVal['quantity'],
"total": "itemVal['total']
}
]
};
result.business.push(jsonObj); // ADDING EACH OBJECT TO YOUR ARRAY
});
});
You want to map the items in snapshot to a new array, so instead of using the forEach method, use the map method and the resulting array it returns:
jsonObj = snapshot.map(function(item) {
return {
"business": [
{
"order_contents": [
{
"id": item['id'],
"name": item['name'],
"price": item['price'],
"quantity": item['quantity'],
"total": item['total']
}
]
}
]
}
});
I have an array like this in Javascript. Something like this
[
{
"id": 1,
"facilities": [
{
"id": 10,
"name": "Wifi",
"label": "Wifi"
},
{
"id": 12,
"name": "Toll",
"label": "Toll"
}
]
},
{
"id": 2,
"facilities": [
{
"id": 10,
"name": "Wifi",
"label": "Wifi"
},
{
"id": 12,
"name": "Toll",
"label": "Toll"
},
{
"id": 13,
"name": "Snack",
"label": "Snack"
}
]
},
{
"id": 3,
"facilities": [
{
"id": 10,
"name": "Wifi",
"label": "Wifi"
},
{
"id": 12,
"name": "Toll",
"label": "Toll"
},
{
"id": 14,
"name": "Petrol",
"label": "Petrol"
}
]
}
]
I want to collect data and grouping data facilities of the array in Javascript, something like this.
"facilities": [
{
"id": 10,
"name": "Wifi",
"label": "Wifi"
},
{
"id": 12,
"name": "Toll",
"label": "Toll"
},
{
"id": 13,
"name": "Snack",
"label": "Snack"
},
{
"id": 14,
"name": "Petrol",
"label": "Petrol"
}
]
So, basically, group by facilities. I just don't know how to handle the grouping of similar facilities values.
Assuming the facility ids are unique:
const facilities = input.reduce((memo, entry) => {
entry.facilities.forEach((f) => {
if (!memo.some((m) => m.id === f.id)) {
memo.push(f)
}
})
return memo
}, [])
You can iterate through all rows and collect (id, entity) map.
Index map allows us to not search already collected entities every time.
Then you can convert it to an array with object keys mapping.
let input = [
{"id": 1, "facilities": [{"id": 10, "name": "Wifi", "label": "Wifi"}, {"id": 12, "name": "Toll", "label": "Toll"} ] },
{"id": 2, "facilities": [{"id": 10, "name": "Wifi", "label": "Wifi"}, {"id": 12, "name": "Toll", "label": "Toll"}, {"id": 13, "name": "Snack", "label": "Snack"} ] },
{"id": 3, "facilities": [{"id": 10, "name": "Wifi", "label": "Wifi"}, {"id": 12, "name": "Toll", "label": "Toll"}, {"id": 14, "name": "Petrol", "label": "Petrol"} ] }
];
let index = input.reduce((res, row) => {
row.facilities.forEach(f => res[f.id] = f);
return res;
}, {});
let result = Object.keys(index).map(id => index[id]);
console.log({facilities: result});
You could use a Set for flagging inserted objects with the given id.
var data = [{ id: 1, facilities: [{ id: 10, name: "Wifi", label: "Wifi" }, { id: 12, name: "Toll", label: "Toll" }] }, { id: 2, facilities: [{ id: 10, name: "Wifi", label: "Wifi" }, { id: 12, name: "Toll", label: "Toll" }, { id: 13, name: "Snack", label: "Snack" }] }, { id: 3, facilities: [{ id: 10, name: "Wifi", label: "Wifi" }, { id: 12, name: "Toll", label: "Toll" }, { id: 14, name: "Petrol", label: "Petrol" }] }],
grouped = data.reduce(
(s => (r, a) => (a.facilities.forEach(b => !s.has(b.id) && s.add(b.id) && r.push(b)), r))(new Set),
[]
);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The solution using Array.prototype.reduce() and Set object:
var data = [{"id": 1,"facilities": [{"id": 10,"name": "Wifi","label": "Wifi"},{"id": 12,"name": "Toll","label": "Toll"}]},{"id": 2,"facilities": [{"id": 10,"name": "Wifi","label": "Wifi"},{"id": 12,"name": "Toll","label": "Toll"},{"id": 13,"name": "Snack","label": "Snack"}]},{"id": 3,"facilities": [{"id": 10,"name": "Wifi","label": "Wifi"},{"id": 12,"name": "Toll","label": "Toll"},{"id": 14,"name": "Petrol","label": "Petrol"}]}
];
var ids = new Set(),
result = data.reduce(function (r, o) {
o.facilities.forEach(function(v) { // iterating through nested `facilities`
if (!ids.has(v.id)) r.facilities.push(v);
ids.add(v.id); // saving only items with unique `id`
});
return r;
}, {facilities: []});
console.log(result);
const input = [
{
"id": 1,
"facilities": [
{
"id": 10,
"name": "Wifi",
"label": "Wifi"
},
{
"id": 12,
"name": "Toll",
"label": "Toll"
}
]
},
{
"id": 2,
"facilities": [
{
"id": 10,
"name": "Wifi",
"label": "Wifi"
},
{
"id": 12,
"name": "Toll",
"label": "Toll"
},
{
"id": 13,
"name": "Snack",
"label": "Snack"
}
]
},
{
"id": 3,
"facilities": [
{
"id": 10,
"name": "Wifi",
"label": "Wifi"
},
{
"id": 12,
"name": "Toll",
"label": "Toll"
},
{
"id": 14,
"name": "Petrol",
"label": "Petrol"
}
]
}
]
const result = []
const idx = []
for (const item of input) {
for (const facilityItem of item.facilities) {
if (!idx.includes(facilityItem.id)) {
idx.push(facilityItem.id)
result.push(facilityItem)
}
}
}
console.log(result)
A very simple and easily understood approach.
const data = [{
"id": 1,
"facilities": [{
"id": 10,
"name": "Wifi",
"label": "Wifi"
},
{
"id": 12,
"name": "Toll",
"label": "Toll"
}
]
},
{
"id": 2,
"facilities": [{
"id": 10,
"name": "Wifi",
"label": "Wifi"
},
{
"id": 12,
"name": "Toll",
"label": "Toll"
},
{
"id": 13,
"name": "Snack",
"label": "Snack"
}
]
},
{
"id": 2,
"facilities": [{
"id": 10,
"name": "Wifi",
"label": "Wifi"
},
{
"id": 12,
"name": "Toll",
"label": "Toll"
},
{
"id": 14,
"name": "Petrol",
"label": "Petrol"
}
]
}
];
let o = {};
let result = [];
data.forEach((d) => {
d.facilities.forEach((f) => {
o[f.id] = f;
});
});
for (let r in o) {
result.push(o[r]);
}
console.log(result);