Calculate array subtotals by category [duplicate] - javascript

This question already has answers here:
Better way to sum a property value in an array
(20 answers)
ES6 Sum by object property in an array
(4 answers)
Closed 2 years ago.
I have an array:
const expenses = [
{ key: '1', sum: '100', category: 'car' },
{ key: '2', sum: '200', category: 'food'},
{ key: '3', sum: '300', category: 'furniture'},
{ key: '4', sum: '400', category: 'food'},
{ key: '5', sum: '700', category: 'car' },
]
How can I get new array or objects with total amount of certain categories?
Like
newArray = [
{category: 'car' totalSum:800},
{category: 'food' totalSum:600},
{category: 'furniture' totalSum:300}
]
Thanks for any suggestions.

Use Array.prototype.reduce():
const expenses = [{key:'1',sum:'100',category:'car'},{key:'2',sum:'200',category:'food'},{key:'3',sum:'300',category:'furniture'},{key:'4',sum:'400',category:'food'},{key:'5',sum:'700',category:'car'},],
result = Object.values(expenses.reduce((r, {category, sum}) =>
(r[category] = {category, totalSum: (r[category]?.totalSum || 0)+ +sum}, r), {}))
console.log(result)
.as-console-wrapper{min-height:100%;}

Related

How to remap array in React [duplicate]

This question already has answers here:
How to rename properties of objects in array in javascript?
(5 answers)
Closed 4 months ago.
How to do a remapo for new objects like:
...
const inputArr = [
{id: '1', name: "test1", routeName: "somethig/something"},
{id: '2', name: "something2", routeName: "foo/bar"},
{id: '3', name: "someanothrelement", routeName: "test/test"}
]
//to =>
const resultStructureArr = [
{ id: '1', value: 'somethig/something', label: 'test1' },
{ id: '2', value: 'foo/bar', label: 'something2' },
{ id: '3', value: 'test/test', label: 'someanothrelement' },
];
...
Here is the jsfiddle
Just using map() can do it
const inputArr = [
{id: '1', name: "test1", routeName: "somethig/something"},
{id: '2', name: "something2", routeName: "foo/bar"},
{id: '3', name: "someanothrelement", routeName: "test/test"}
]
let result = inputArr.map(a => ({'id':a.id,'label':a.name,'value':a.routeName}))
console.log(result)
We can use traditional for loop for this. Where we may loop to the length of list and for each iteration we may add new object into result array using Array.prototype.push method. Secondly we are doing the same thing with foreach loop. Third I'm using Array.prototype.map method, Which creates a new result for each iteration, in our case we are returning our new object. Lastly we are using Array.prototype.reduce method, with this method we can initialize a starting value which in my case I'm using empty array, then for each iteration I'm pushing a new object in that array and returning it.
const inputArr = [
{ id: "1", name: "test1", routeName: "somethig/something" },
{ id: "2", name: "something2", routeName: "foo/bar" },
{ id: "3", name: "someanothrelement", routeName: "test/test" },
];
// Using for loop
let result = [];
for (let i = 0; i < inputArr.length; i++) {
result.push({
id: inputArr[i].id,
value: inputArr[i].routeName,
label: inputArr[i].name,
});
}
console.log(result);
result = [];
// using foreach loop
inputArr.forEach((item) => {
result.push({ id: item.id, label: item.name, value: item.routeName });
});
console.log(result);
result = [];
// using map
result = inputArr.map((item) => ({
id: item.id,
label: item.name,
value: item.routeName,
}));
console.log(result);
result = [];
// using reduce
result = inputArr.reduce((acc, curr) => {
acc.push({ id: curr.id, label: curr.name, value: curr.routeName });
return acc;
}, []);
console.log(result);

How to aggregate objects that exist in two array? [duplicate]

This question already has an answer here:
Javascript: Merge Array of Objects, summing values with same key
(1 answer)
Closed 10 months ago.
if I have two (large) arrays that specify a key and a numeric value
var a = [
{ gtin: 'a1', quantity: 1 },
{ gtin: 'a3', quantity: 1 },
];
var b = [
{ gtin: 'a1', quantity: 1 },
{ gtin: 'a4', quantity: 1 },
];
what is the easiest way to get a single array that sums the quantities?
(Lodash ok, fewest iterations over array preferred)
ie
[
{ gtin: 'a1', quantity: 2 },
{ gtin: 'a3', quantity: 1 },
{ gtin: 'a4', quantity: 1 },
];
You could use a Map to keep track of gtin and its accumulated quantity, and then transform it back to array
const a = [
{ gtin: 'a1', quantity: 1 },
{ gtin: 'a3', quantity: 1 },
];
const b = [
{ gtin: 'a1', quantity: 1 },
{ gtin: 'a4', quantity: 1 },
];
const res = Array.from(
a
.concat(b)
.reduce(
(map, el) => map.set(el.gtin, (map.get(el.gtin) || 0) + el.quantity),
new Map()
)
).map(([gtin, quantity]) => ({ gtin, quantity }));
console.log(res);
References
Map

Compare Javascript Object field with another Object field [duplicate]

This question already has answers here:
Merge two array of objects based on a key
(23 answers)
Closed last year.
I have two Objects one of them has the Store Name and the other object has the Price for an item along with the Store ID on both objects. Such as;
obj1 = [
{id: 1,name: "Store1"},
{id: 2,name: "Store2"},
{id: 3,name: "Store3"}
];
obj2= [
{ id: 1, price: 100 },
{ id: 2, price: 200 },
{ id: 3, price: 300 }
];
What I want to achieve is that compare obj1 id with obj2 id if they are the same get the price and the store name from the same id. What is the best way to achieve this? I have been trying to use Array.map or filter but can't really make it work. Thank you!
You can use map & find
const obj1 = [{
id: 1,
name: "Store1"
},
{
id: 2,
name: "Store2"
},
{
id: 3,
name: "Store3"
},
{
id: 4,
name: "Store3"
}
];
const obj2 = [{
id: 1,
price: 100
},
{
id: 2,
price: 200
},
{
id: 3,
price: 300
}
];
const newData = obj1.map((item, index) => {
return {
...item,
// if the item exist in obj2 then get the price else assign empty string
price: obj2.find(elem => elem.id === item.id) ? .price || ''
}
});
console.log(newData)

Remove duplicates from array of objects - Javascript [duplicate]

This question already has answers here:
How to remove all duplicates from an array of objects?
(77 answers)
Closed 2 years ago.
Hi I'm trying to remove duplicates from array of objects. But that is not working as expected.
This is my array:
const arr = [{
PData: [{
id: '1',
name: 'Book'
},
{
id: '2',
name: 'Bag'
},
{
id: '2',
name: 'Bag'
},
]
}]
const RemoveDuplicates = (array, key) => {
return array.reduce((arr, item) => {
const removed = arr.filter(i => i[key] !== item[key]);
return [...removed, item];
}, []);
};
var result = RemoveDuplicates(arr, 'id')
console.log(result);
Expected output:
[{
PData: [{
id: '1',
name: 'Book'
},
{
id: '2',
name: 'Bag'
},
]
}]
Based on id it supposed to remove duplicates but this is not happening currently..I know that couple of questions are existed regarding this but nothing is working for me. So anyone plz suggest me how to do.
You can use filter here is how on id and name.
const arr = [{
PData: [{
id: '1',
name: 'Book'
},
{
id: '2',
name: 'Bag'
},
{
id: '2',
name: 'Bag'
},
]
}]
arr[0].PData = Object.values(arr[0].PData).filter((v,i,a)=>a.findIndex(t=>(t.id === v.id && t.name=== v.name))===i)
console.log(arr[0].PData);

How to map an array of objects by a given field? [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 3 years ago.
I have an array of objects:
let tempArray = [
{
id: '1',
name: 'Tom',
age: 11
},
{
id: '2',
name: 'Jerry',
age: 13
}
...
]
How can I create a new array that would contain only name fields from all objects of the tempArray array?
Trying using map()
let tempArray = [
{
id: '1',
name: 'Tom',
age: 11
},
{
id: '2',
name: 'Jerry',
age: 13
}
]
const res = tempArray.map(i => i.name)
console.log(res)

Categories

Resources