SUM AND GROUPING JSON DATA USING JAVASCRIPT [duplicate] - javascript

This question already has answers here:
How to group by and sum an array of objects? [duplicate]
(2 answers)
Sum JavaScript object propertyA values with the same object propertyB in an array of objects
(12 answers)
Group by, and sum, and generate an object for each array in JavaScript
(4 answers)
ES6 Implementation of Group By and SUM
(4 answers)
Javascript array of objects group and sum items
(4 answers)
Closed last year.
Sorry if this has been asked before, but I couldn't find a good example of what I'm trying to accomplish. Maybe I'm just not searching for the right thing. Please correct me if there's an explanation of this somewhere.
so let's says I have a data like this :
data = [
{"no":1,"location":"New York","transaction":3000},
{"no":2,"location":"Tokyo","transaction":3000},
{"no":3,"location":"New York","transaction":3000},
{"no":4,"location":"Amsterdam","transaction":3000},
{"no":5,"location":"Manchester","transaction":3000},
{"no":6,"location":"New York","transaction":3000},
{"no":7,"location":"Tokyo","transaction":3000},
{"no":8,"location":"Tokyo","transaction":3000},
{"no":9,"location":"New York","transaction":3000},
{"no":10,"location":"Amsterdam","transaction":3000}
]
what i wanted to is an output like this :
result = [
{"location":"New York","transaction":12000},
{"location":"Tokyo","transaction":9000},
{"location":"Amsterdam","transaction":6000}
{"location":"Manchester","transaction":3000}
]
so what i wanted to do is grouping the data based on location and sum the transaction where the location is same and push the data to another array. i don't know where to start, need some help to solve this or any suggestion to solve this using Javascript. thank you

Working Demo :
// Input array
const data = [
{"no":1,"location":"New York","transaction":3000},
{"no":2,"location":"Tokyo","transaction":3000},
{"no":3,"location":"New York","transaction":3000},
{"no":4,"location":"Amsterdam","transaction":3000},
{"no":5,"location":"Manchester","transaction":3000},
{"no":6,"location":"New York","transaction":3000},
{"no":7,"location":"Tokyo","transaction":3000},
{"no":8,"location":"Tokyo","transaction":3000},
{"no":9,"location":"New York","transaction":3000},
{"no":10,"location":"Amsterdam","transaction":3000}
];
// result array
const resultArr = [];
// grouping by location and resulting with an object using Array.reduce() method
const groupByLocation = data.reduce((group, item) => {
const { location } = item;
group[location] = group[location] ?? [];
group[location].push(item.transaction);
return group;
}, {});
// Finally calculating the sum based on the location array we have.
Object.keys(groupByLocation).forEach((item) => {
groupByLocation[item] = groupByLocation[item].reduce((a, b) => a + b);
resultArr.push({
'location': item,
'transaction': groupByLocation[item]
})
})
console.log(resultArr)

Related

array.push() and splite in Array of arrays [duplicate]

This question already has answers here:
Split array into chunks
(73 answers)
Closed 6 days ago.
This post was edited and submitted for review 6 days ago.
I'm using arrayofArrays[0].push() inside a for loop in order to add an Object to the Array0 inside arrayofArrays.
Now I'd like that when Array0 has reached 2 element, the next element will be pushed to Array1, in order to achieve this situation:
var arrayofArrays = [[Obj0,Obj1],[Obj2,Obj3],[Obj4,Obj5], ...];
Sample code:
var arrayofArrays = [[]];
for(data in Data){
var Obj = {"field1":data[0], "field2":data[1], "field3":data[2] }
arrayofArrays[0].push(Obj); // need to pass to arrayofArrays[1] when arrayofArrays[0] has 2 Obj...
}
(I don't need to split an existing array, I'm adding Object to an array, and want them to split in sub-arrays while adding them)
Here is a functional programming approach to your question to unflatten an array:
const arr = Array.from(Array(6).keys()); // [0, 1, 2, 3...]
let t;
let arrOfArr = arr.map((v, idx) => {
if(idx % 2) {
return [t, v];
} else {
t = v;
return null;
}
}).filter(Boolean);
console.log({
arr,
arrOfArr,
});
Note: Array.from(Array(6).keys()) is just for demo. Replace this with any array of objects you like

Create a array of objects by grouping objects conditionally [duplicate]

This question already has answers here:
Group array items using object
(19 answers)
How can I group an array of objects by key?
(32 answers)
Closed last month.
I am trying to create a new array of objects by comparing two arrays.One array contains the ids to be compared and the other contains the dataset which should be compared with the first array are a new array of object must be created.
Let me explain this in detail
Consider array 1:
['1','2']
Array 2
[{name:'Linus',id:'1'},{name:'Anthony',id:'1'},{name:'Jake',id:'2'},{name:'Eva',id:'2'}]
What I am expecting as a output is:
[
{id:'1',users:[{name:'Linus',id:'1'},{name:'Anthony',id:'1'}]},
{id:'2',users:[{name:'Jake',id:'2'},{name:'Eva',id:'2'}
]
I am not sure what has to be done.
Something like this for example
const ids = ['1','2'];
const users = [{name:Linus,id:'1'},{name:Anthony,id:'1'},{name:Jake,id:'2'},{name:Eva,id:'2'}];
const groups = ids.map(id =>{
return {
id,
users: users.filter(u => u.id === id)
}
})
const groupBy = ['1','2'];
const data = [{name:'Linus',id:'1'},{name:'Anthony',id:'1'},{name:'Jake',id:'2'},{name:'Eva',id:'2'}];
const result = groupBy.map(id => {
return {
id,
users: data.filter(item => item.id == id),
}
})
console.log(result);
Try this code

JavaScript Array: Order Nested Object by Key [duplicate]

This question already has answers here:
Sorting an array of objects by property values
(35 answers)
How to sort strings in JavaScript
(16 answers)
Sort Array by ISO 8601 date
(8 answers)
Closed last year.
I have the following nested object. I would like to iterate through every item (latest.sentTime) and then sort the object itself by "sentTime". So that the most recent message is on top. How can I achieve this?
In the following example, "0" and "1" need to be swapped basically, since "1" has a more recent "sentTime".
Using Array#map, iterate over the array to get latest.sentTime
Using Array#sort and Date, sort the items
const arr = [
{ latest: { sentTime: '2022-02-05T19:15:32.000Z' } },
{ latest: { sentTime: '2022-02-06T22:12:00.000Z' } }
];
const sentTimes = arr
.map(({ latest }) => latest.sentTime)
.sort((a, b) => new Date(b) - new Date(a));
console.log(sentTimes);

How to remove dublicate values from array of objects using javaScript? [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 1 year ago.
I have this array of objects, my aim is to remove dublicate values from values array, I want the result to be [{name:'test1', values:['35,5', '35,2','35,3']}, {name:'test2', values:['33,2', '34,3', '32,5']}]
I have tried following solution but it does not works, Do you have any suggestions? Thanks in advance
let arr = [{name:'test1', values:['35,5', '35,2', '35,2', '35,3', '35,5']},
{name:'test2', values:['35,1', '35,1', '33,2', '34,3', '32,5']}]
let uniqueArray = arr.values.filter(function(item, pos) {
return arr.values.indexOf(item.values) == pos;
})
console.log(uniqueArray)
}
}
You can easily remove duplicates from an Array by creating a new Set based off it.
Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection
If you want the result in an array, just use spread syntax for that, for example:
let arr = [{
name: 'test1',
values: ['35,5', '35,2', '35,2', '35,3', '35,5']
},
{
name: 'test2',
values: ['35,1', '35,1', '33,2', '34,3', '32,5']
}
];
const uniqueArr = arr.reduce((accum, el) => {
// Copy all the original object properties to a new object
const obj = {
...el
};
// Remove the duplicates from values by creating a Set structure
// and then spread that back into an empty array
obj.values = [...new Set(obj.values)];
accum.push(obj);
return accum;
}, []);
uniqueArr.forEach(el => console.dir(el));

Javascript to Group Array of Object into combination of two values [duplicate]

This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Create Multilevel groups from an Array of Objects
(2 answers)
Closed 4 years ago.
var data=[
{custType:1,code:'savings',efDate:'2/3/19',exDate'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'current',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'current',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'}
];
expected results
var modifiedData=[
[
savings=[ {custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'}
],
current=[ {custType:1,code:'current',efDate:'2/3/19',exDate:'2/3/19'} ]
],
[
savings=[ {custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'} ],
current=[ {custType:2,code:'current',efDate:'2/3/19',exDate:'2/3/19'} ]
]
];
as i am trying to find a group with (custType and code), i am not able to generate the expected result. Which method i should use here? can i use reduce or groupBy. I am confused about it.
You could build up a nested hashtable:
const hash = {};
for(const value of data) {
const group = hash[value.custType] || (hash[value.custType] = {});
const group2 = group[value.code] || (group[value.code] = []);
group2.push(value);
}
const result = Object.values(hash).map(Object.values);

Categories

Resources