I have two array of objects, and I want to sum the object that have a same key (in this case, id), and if there is no match key, then just create a new one.. I'm sorry if I am not explaining it clearly, I am new to JavaScript/Array/Object thing...
var dataOne = [ { id:"1", total: 10, win: 5 }, { id:"2", total: 5, win: 1 }, { id:"3", total: 5, win: 2 } ]
and
var dataTwo = [ { id:"1", total: 5, win: 2 }, { id:"2", total: 2, win: 3 }, { id:"5", total: 5, win: 4 } ]
Expected result:
var combinedData = [ { id:"1", total: 15, win: 7 }, { id:"2", total: 7, win: 4 }, { id:"3", total: 5, win: 2 }, { id:"5", total: 5, win: 4 } ]
I have tried to use the solution from Sum all data in array of objects into new array of objects
but, apparently the type of data is kind of different
So, I tried to use this method from Javascript - Sum of two object with same properties
function sumObjectsByKey(...objs) {
for (var prop in n) {
if (acc.hasOwnProperty(prop)) acc[prop] += n[prop];
else acc[prop] = n[prop];
}
return acc;
}
and
var combinedData = sumObjectsByKey(dataOne, dataTwo);
But apparently, that method won't work for an array of objects.
I get
{0: "0[object Object][object Object]", 1: "0[object Object][object Object]", 2: "0[object Object][object Object]"}
as a result.
Combine both arrays by spread into Array.concat(). Reduce the items into a Map, while combining the current item, with the item that already exists in the Map. Convert back to array by spreading the Map.values() iterator:
// utility function to sum to object values (without the id)
const sumItem = ({ id, ...a }, b) => ({
id,
...Object.keys(a)
.reduce((r, k) => ({ ...r, [k]: a[k] + b[k] }), {})
});
const sumObjectsByKey = (...arrs) => [...
[].concat(...arrs) // combine the arrays
.reduce((m, o) => // retuce the combined arrays to a Map
m.set(o.id, // if add the item to the Map
m.has(o.id) ? sumItem(m.get(o.id), o) : { ...o } // if the item exists in Map, sum the current item with the one in the Map. If not, add a clone of the current item to the Map
)
, new Map).values()]
const dataOne = [ { id:"1", total: 10, win: 5 }, { id:"2", total: 5, win: 1 }, { id:"3", total: 5, win: 2 } ]
const dataTwo = [ { id:"1", total: 5, win: 2 }, { id:"2", total: 2, win: 3 }, { id:"5", total: 5, win: 4 } ]
const result = sumObjectsByKey(dataOne, dataTwo)
console.log(result)
I'd suggest Array.reduce here. In the body of the reduction function, if the id isn't in the result accumulator, add it, then increment all of the values for each property in the object.
var dataOne = [ { id:"1", total: 10, win: 5 }, { id:"2", total: 5, win: 1 }, { id:"3", total: 5, win: 2 } ]
var dataTwo = [ { id:"1", total: 5, win: 2 }, { id:"2", total: 2, win: 3 }, { id:"5", total: 5, win: 4 } ]
var sumObjectsByKey = (...objs) =>
Object.values(objs.reduce((a, e) => {
a[e.id] = a[e.id] || {id: e.id};
for (const k in e) {
if (k !== "id") {
a[e.id][k] = a[e.id][k] ? a[e.id][k] + e[k] : e[k];
}
}
return a;
}, {}))
;
console.log(sumObjectsByKey(...dataOne, ...dataTwo));
Related
Suppose if i have an input data like:
[
{
name: 'rohan',
subName: [
{
name: 'rohan_abc',
subName: [
{
name: 'rohan_abc_abc',
subName: []
}]
},
{
name: 'rohan_abc',
subName: []
},{
name: 'rohan_abc_abc',
subName: []
}]
},
{
name: 'rohan',
subName: [
{
name: 'rohan_abc',
subName: [
{
name: 'rohan_abc_abc',
subName: [{
name: 'rohan_abc_abc_abc',
subName: []
}]
}]
},
{
name: 'rohan_bcd',
subName: []
},{
name: 'rohan_abc_abc',
subName: []
}]
}]
The output should be like
[
{
name: 'rohan',
count: 2,
subName: [
{
name: 'rohan_abc',
count: 3,
subName: [
{
name: 'rohan_abc_abc',
count: 2
subName: [
{
name: 'rohan_abc_abc_abc',
count: 1
}]
}]
},
{
name: 'rohan_abc_abc',
count: 2
subName: []
},
{
name: 'rohan_bcd',
count: 1
}]
}]
if the same name is repeated in the same layer then the count should increase. Otherwise, the count should remain 1.
In above example: rohan_abc_abc is occurred at 2 different levels so that they have different count at respective level.
Hoping to get positive feedbacks. Thank you!!!
Array Reduce Information on MDN
Array reduce takes 2 parameters, a callback function with 4 arguments and secondly an initial value.
The callback functions takes up to 4 arguments previousValue, currentValue, currentIndex, array. we focus on the first two arguments and the initialValue parameter.
Where previousValue is the previous value OR the initial value OR undefined;
Where currentValue is the current.
Oke, lets learn reduce!
let arr = [0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xA,0xB,0xC,0xD,0xE, 0xF];
arr.reduce( ( previousValue, currentValue ) => { return previousValue; });
//returns 0 ( as it should, up to you to figure out why )
Now we will use initialValue, the second parameter of de reduce function.
arr.reduce( ( accumulator, currentValue ) => {
accumulator.push(currentValue*2);
return accumulator;
}, []);
// returns [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
So as you can see, we used the second parameterof the reduce function with a empty new array. We push the current value and multiply times 2. And return of course we return the accumulator/previous value.
So if we apply that logic to your array and do some checks..
aa.reduce((accumulator, currentValue) => {
// get all names in the accumulator
let nameMap = accumulator.map((element) => {
return element.name;
});
let indexOfcurrentValueName = nameMap.indexOf(currentValue.name);
// check if already exist in accymulator
if (indexOfcurrentValueName > -1) {
//Is already in
// concat subName
accumulator[indexOfcurrentValueName].subName = accumulator[indexOfcurrentValueName].subName.concat( currentValue.subName);
} else {
//not in put currentValue in accumulator
accumulator.push(currentValue);
}
return accumulator;
}, []);
if we put this inline function in a function statement and call it after we concat accumulator[indexOfcurrentValueName].subName.reduce( reduceFn, []); than you will get what you want.
Edit 17 Sept 2021:
//the reduce function
function reduceFn(accumulator, currentValue) {
// get all names in the accumulator
let nameMap = accumulator.map((element) => {
return element.name;
});
let indexOfcurrentValueName = nameMap.indexOf(currentValue.name);
// check if already exist in accymulator
if (indexOfcurrentValueName > -1) {
//Is already in
// concat subName
accumulator[indexOfcurrentValueName].subName = accumulator[indexOfcurrentValueName].subName.concat( currentValue.subName);
/* ---- */
// this will make the call back to the reduce function but for it's children. this is for level 2,3,4,5,6,7, infinity
accumulator[indexOfcurrentValueName].subName.reduce( reduceFn, []);
/* ---- */
} else {
//not in put currentValue in accumulator
accumulator.push(currentValue);
}
return accumulator;
}
// and here we kick start things this is for level 1
arr.reduce( reduceFn, []);
I have an array of arrays, which contain objects, would like to get the value of a certain key and return it as a big array, have tried a nested map but it returns multiple array's rather than a single array.
const items = [
{
id: 1,
sub_items: [
{
id: 1
},
{
id: 2
},
{
id: 3
}
]
},
{
id: 2,
sub_items: [
{
id: 4
},
{
id: 5
},
{
id: 6
}
]
}
]
const subItemIDs = items.map( (item) =>
item.sub_items.map( (subItem) => subItem.id )
)
console.log(subItemIDs);
Expected output
[1, 2, 3, 4, 5, 6]
Actual output
[ [1,2,3], [4,5,6] ]
You can use arrays.flat(). I can provide more specific code once output is mentioned in the question
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]
You could take Array#flatMap to get a flat array from nested arrays.
const
items = [{ id: 1, sub_items: [{ id: 1 }, { id: 2 }, { id: 3 }] }, { id: 2, sub_items: [{ id: 4 }, { id: 5 }, { id: 6 }] }],
subItemIDs = items.flatMap(({ sub_items }) => sub_items.map(({ id }) => id));
console.log(subItemIDs);
Achieved this with:
const items = [
{
id: 1,
sub_items: [
{
id: 1
},
{
id: 2
},
{
id: 3
}
]
},
{
id: 2,
sub_items: [
{
id: 4
},
{
id: 5
},
{
id: 6
}
]
}
]
const subItemIDs = [].concat(...items.map( (item) =>
item.sub_items.map( (subItem) => subItem.id )
))
console.log(subItemIDs);
Sometimes, the obvious is the easiest:
Given a data structure that looks like this
const items = [
{ id: 1, sub_items: [ { id: 1 }, { id: 2 }, { id: 3 }, ] },
{ id: 2, sub_items: [ { id: 4 }, { id: 5 }, { id: 6 }, ] },
];
A trivial function like this
function extract_item_ids( items ) {
const ids = [];
for ( const item of items ) {
for ( const {id} of sub_items ) {
ids.push(id);
}
}
return ids;
}
should do the trick. If you want to collect the ids from a tree of any depth, it's just as easy:
function extract_item_ids( items ) {
const ids = [];
const pending = items;
while ( pending.length > 0 ) {
const item = pending.pop();
ids.push(item.id);
pending.push(...( item.sub_items || [] ) );
}
return ids;
}
And collecting the set of discrete item IDs is no more difficult:
If you want to collect the ids from a tree of any depth, it's just as easy:
function extract_item_ids( items ) {
const ids = new Set();
const pending = [...items];
while ( pending.length > 0 ) {
const item = pending.pop();
ids.add(item.id);
pending.push(...( item.sub_items || [] ) );
}
return Array.from(ids);
}
As is the case with most things JavaScript, you have several options. Some are more efficient than others, others have a certain stylistic purity, others might better speak to your fancy. Here are a few:
Array.flat
With array flat you can take your original code and have the JS Engine flatten the array down to a one-dimensional array. Simply append .flat() onto the end of your map.
const items = [
{ id: 1, sub_items: [ { id: 1 }, { id: 2 }, { id: 3 }, ] },
{ id: 2, sub_items: [ { id: 4 }, { id: 5 }, { id: 6 }, ] },
];
const subItemIds = items.map( (item) =>
item.sub_items.map( (subItem) => subItem.id )
).flat()
console.log(subItemIds);
Array.reduce
Another method is to use reduce to iterate over the object and build an accumulation array using Array.reduce. In the example below, when pushing onto the array, the spread operator (...) is used to break the array into elements.
const items = [
{ id: 1, sub_items: [ { id: 1 }, { id: 2 }, { id: 3 }, ] },
{ id: 2, sub_items: [ { id: 4 }, { id: 5 }, { id: 6 }, ] },
];
const subItemIds = items.reduce((arr,item) => (
arr.push(...item.sub_items.map((subItem) => subItem.id)), arr
),[])
console.log(subItemIds);
Other
Other answers here make use of custom functions or Array.flatMap, which should be explored as they could lead to more readable and efficient code, depending on the program's needs.
I have javascript array object as below. My need is to sum value base on seach id in the array object.
var array = [
{ id: 1, val: 10 },
{ id: 2, val: 25 },
{ id: 3, val: 20 },
{ id: 1, val: 30 },
{ id: 1, val: 25 },
{ id: 2, val: 10 },
{ id: 1, val: 20 }
],
For example sum of value for id 1 is 10 + 30 + 25 + 20 = 85 , It may be something link linq but I'm not sure in javascript. Thanks for all answers.
You can use a combination of filter and reduce to get the result you want:
sumOfId = (id) => array.filter(i => i.id === id).reduce((a, b) => a + b.val, 0);
Usage:
const sumOf1 = sumOfId(1); //85
Reading material:
Array.prototype.filter
Array.prototype.reduce
A way to do it with a traditional for loop
var array = [
{ id: 1, val: 10 },
{ id: 2, val: 25 },
{ id: 3, val: 20 },
{ id: 1, val: 30 },
{ id: 1, val: 25 },
{ id: 2, val: 10 },
{ id: 1, val: 20 }
];
var sums = {};
for (var i = 0; i < array.length; i++) {
var obj = array[i];
sums[obj.id] = sums[obj.id] === undefined ? 0 : sums[obj.id];
sums[obj.id] += parseInt(obj.val);
}
console.log(sums);
running example
You can use reduce() and findIndex()
var array = [
{ id: 1, val: 10 },
{ id: 2, val: 25 },
{ id: 3, val: 20 },
{ id: 1, val: 30 },
{ id: 1, val: 25 },
{ id: 2, val: 10 },
{ id: 1, val: 20 }
];
let res = array.reduce((ac,a) => {
let ind = ac.findIndex(x => x.id === a.id);
ind === -1 ? ac.push(a) : ac[ind].val += a.val;
return ac;
},[])
console.log(res);
JS noob here ... I guess something like this should be here too :-)
let newArray = {}
array.forEach((e) => {
!newArray[e.id] && (newArray[e.id] = 0);
newArray[e.id] += e.val;
});
You can loop on the array and check the ids.
var array = [
{ id: 1, val: 10 },
{ id: 2, val: 25 },
{ id: 3, val: 20 },
{ id: 1, val: 30 },
{ id: 1, val: 25 },
{ id: 2, val: 10 },
{ id: 1, val: 20 }
];
var sum = 0;
var id = 1;
$.each(array, function(index, object){
if (object.id == id) {
sum += object.val;
}
});
console.log(sum);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Using Array#reduce and Map you can get the sum for each id like so. This also uses destructuring to have quicker access to properties.
const data=[{id:1,val:10},{id:2,val:25},{id:3,val:20},{id:1,val:30},{id:1,val:25},{id:2,val:10},{id:1,val:20}];
const res = data.reduce((a,{id,val})=>{
return a.set(id, (a.get(id)||0) + val);
}, new Map())
console.log(res.get(1));
console.log(res.get(2));
If you wanted to output all the sums, then you need to use Array#from
const data=[{id:1,val:10},{id:2,val:25},{id:3,val:20},{id:1,val:30},{id:1,val:25},{id:2,val:10},{id:1,val:20}];
const res = Array.from(
data.reduce((a,{id,val})=>{
return a.set(id, (a.get(id)||0) + val);
}, new Map())
);
console.log(res);
If the format should be similar as to your original structure, you need to add a Array#map afterwards to transform it.
const data=[{id:1,val:10},{id:2,val:25},{id:3,val:20},{id:1,val:30},{id:1,val:25},{id:2,val:10},{id:1,val:20}];
const res = Array.from(
data.reduce((a,{id,val})=>{
return a.set(id, (a.get(id)||0) + val);
}, new Map())
).map(([id,sum])=>({id,sum}));
console.log(res);
You could take GroupBy from linq.js with a summing function.
var array = [{ id: 1, val: 10 }, { id: 2, val: 25 }, { id: 3, val: 20 }, { id: 1, val: 30 }, { id: 1, val: 25 }, { id: 2, val: 10 }, { id: 1, val: 20 }],
result = Enumerable
.From(array)
.GroupBy(null, null, "{ id: $.id, sum: $$.Sum('$.val') }", "$.id")
.ToArray();
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>
Here is another option, introducing an Array.prototype.sum helper:
Array.prototype.sum = function (init = 0, fn = obj => obj) {
if (typeof init === 'function') {
fn = init;
init = 0;
}
return this.reduce(
(acc, ...fnArgs) => acc + fn(...fnArgs),
init
);
};
// .sum usage examples
console.log(
// sum simple values
[1, 2, 3].sum(),
// sum simple values with initial value
[1, 2, 3].sum(10),
// sum objects
[{ a: 1 }, { a: 2 }, { a: 3 }].sum(obj => obj.a),
// sum objects with initial value
[{ a: 1 }, { a: 2 }, { a: 3 }].sum(10, obj => obj.a),
// sum custom combinations
[{ amount: 1, price: 2 }, { amount: 3, price: 4 }]
.sum(product => product.amount * product.price)
);
var array = [{ id: 1, val: 10 }, { id: 2, val: 25 }, { id: 3, val: 20 }, { id: 1, val: 30 }, { id: 1, val: 25 }, { id: 2, val: 10 }, { id: 1, val: 20 }];
// solutions
console.log(
array.filter(obj => obj.id === 1).sum(obj => obj.val),
array.filter(({id}) => id === 1).sum(({val}) => val),
array.sum(({id, val}) => id === 1 ? val : 0)
);
references:
Array.prototype.reduce
Array.prototype.filter
Arrow functions used in sum(obj => obj.val)
Object destructing assignment used in ({id}) => id === 1
Rest parameters used in (acc, ...fnArgs) => acc + fn(...fnArgs)
Conditional (ternary) operator used in id === 1 ? val : 0
I'm trying to get two values (label and data) from my source data array, rename the label value and sort the label and data array in the result object.
If this is my source data...
const sourceData = [
{ _id: 'any', count: 12 },
{ _id: 'thing', count: 34 },
{ _id: 'value', count: 56 }
];
...the result should be:
{ label: ['car', 'plane', 'ship'], data: [12, 34, 56] }
So any should become car, thing should become plane and value should become ship.
But I also want to change the order of the elements in the result arrays using the label values, which should also order the data values.
Let's assume this result is expected:
{ label: ['ship', 'car', 'plane'], data: [56, 12, 34] }
With the following solution there is the need of two variables (maps and order). I thing it would be better to use only one kind of map, which should set the new label values and also the order. Maybe with an array?!
Right now only the label values get ordered, but data values should be ordered in the same way...
const maps = { any: 'car', thing: 'plane', value: 'ship' }; // 1. Rename label values
const result = sourceData.reduce((a, c) => {
a.label = a.label || [];
a.data = a.data || [];
a.label.push(maps[c._id]);
a.data.push(c.count);
return a;
}, {});
result.label.sort((a, b) => {
const order = {'ship': 1, 'car': 2, plane: 3}; // 2. Set new order
return order[a] - order[b];
})
You could move the information into a single object.
const
data = [{ _id: 'any', count: 12 }, { _id: 'thing', count: 34 }, { _id: 'value', count: 56 }],
target = { any: { label: 'car', index: 1 }, thing: { label: 'plane', index: 2 }, value: { label: 'ship', index: 0 } },
result = data.reduce((r, { _id, count }) => {
r.label[target[_id].index] = target[_id].label;
r.data[target[_id].index] = count;
return r;
}, { label: [], data: [] })
console.log(result);
Instead of separating the data into label and data and then sorting them together, you can first sort the data and then transform.
const sourceData = [
{ _id: 'any', count: 12 },
{ _id: 'thing', count: 34 },
{ _id: 'value', count: 56 }
];
const maps = { any: 'car', thing: 'plane', value: 'ship' };
// Rename label values.
let result = sourceData.map(item => ({
...item,
_id: maps[item._id]
}));
// Sort the data.
result.sort((a, b) => {
const order = {'ship': 1, 'car': 2, plane: 3};
return order[a._id] - order[b._id];
})
// Transform the result.
result = result.reduce((a, c) => {
a.label = a.label || [];
a.data = a.data || [];
a.label.push(c._id);
a.data.push(c.count);
return a;
}, {});
console.log(result);
What is the alternative/best way to map through an object key-values without using forEach?
This is what I have currently:
sortObject(source) {
const object = Object.assign({}, source);
Object.keys(object).forEach(key => {
// Sort array by priority (the higher the number, the higher the priority)
object[key] = object[key].sort((a, b) => b.priority - a.priority);
// Limit the array length to the 5
if (object[key].length > 5) {
object[key] = object[key].slice(0, 5);
}
});
return object;
}
source is an object like:
{
base: [
{ id: 1, priority: 5 },
{ id: 2, priority: 10 },
{ id: 3, priority: 1 },
{ id: 4, priority: 5 },
{ id: 5, priority: 15 }
],
extra: [
{ id: 1, priority: 1 },
{ id: 2, priority: 5 },
{ id: 3, priority: 10 }
],
additional: [
{ id: 1, priority: 5 },
{ id: 2, priority: 10 },
{ id: 3, priority: 10 },
{ id: 4, priority: 15 },
{ id: 5, priority: 1 },
{ id: 6, priority: 29 },
{ id: 7, priority: 100 },
{ id: 8, priority: 100 },
{ id: 9, priority: 5 }
]
}
The final output is like:
{
base: [
{ id: 5, priority: 15 },
{ id: 2, priority: 10 },
{ id: 1, priority: 5 },
{ id: 4, priority: 5 },
{ id: 3, priority: 1 }
],
extra: [
{ id: 3, priority: 10 },
{ id: 2, priority: 5 },
{ id: 1, priority: 1 }
],
additional: [
{ id: 7, priority: 100 },
{ id: 8, priority: 100 },
{ id: 6, priority: 29 },
{ id: 4, priority: 15 },
{ id: 2, priority: 10 }
]
}
is there a better/cleaner way to do this?
I'd look at Object.entries (new as of ES2017 but polyfillable) and destructuring in a for-of loop.
If nothing else has access to the arrays on source (which I tend to assume, since sort works in-place, so the code already modifies the original array; but at the same time, source is coming in from outside, so...):
sortObject(source) {
const object = Object.assign({}, source);
for (const [key, array] of Object.entries(object)) {
array.sort((a, b) => b.priority - a.priority);
array.length = Math.min(array.length, 5);
}
return object;
}
If something else has access to those arrays and you shouldn't modify them other than sorting them, then you'll need your original length check and slice:
sortObject(source) {
const object = Object.assign({}, source);
for (const [key, array] of Object.entries(object)) {
array.sort((a, b) => b.priority - a.priority);
if (array.length > 5) {
object[key] = array.slice(0, 5);
}
}
return object;
}
Your code suggests you may not have realized sort works in-place since you were assigning the result back to the original location. If so and you didn't intend to sort the arrays in-place, you'll need to copy the arrays before sorting:
sortObject(source) {
const object = Object.assign({}, source);
for (const [key, array] of Object.entries(object)) {
object[key] = array = array.slice();
array.sort((a, b) => b.priority - a.priority);
array.length = Math.min(array.length, 5);
}
return object;
}
You could replace
object[key] = array = array.slice();
array.sort((a, b) => b.priority - a.priority);
with
object[key] = array = Array.from(array).sort((a, b) => b.priority - a.priority);
if you like, but that'll use an iterator, which is more overhead than slice.
You can also use map for looping the object entries and splice for cutting off the array length:
const getSortedObj = (source) => {
let obj = Object.assign({}, source);
Object.entries(obj).map( entry => {
let [key, arr] = entry;
arr.sort((a, b) => b.priority - a.priority).splice(Math.min(arr.length, 5));
return entry;
});
return obj;
};