Trying to get a sum using reduce method - javascript

I am trying to get the sum of all (a) properties and console.log says NAN
const numbers = [{ a: 1 }, { a: 6 }, { a: 3 }, { d: 4 }, { e: 5 }, { f: 5 }];
const filterNumbers = numbers.reduce((currenttotal, item) => {
return item.a + currenttotal;
}, 0);
console.log(filterNumbers);
is there something wrong?
trying to get the sum of only a keys

Hate to be the person that takes someone's comment and makes an answer out of it, but as #dandavis has suggested, you need to, in someway, default to a value if the 'a' key doensn't exist.
This can be done in a variety of ways:
Short circuit evaluation:
const filterNumbers = numbers.reduce((currenttotal, item) => {
return (item.a || 0) + currenttotal;
}, 0);
The in operator:
const filterNumbers = numbers.reduce((currenttotal, item) => {
return ("a" in item ? item.a : 0) + currenttotal;
}, 0);
Nullish coalescing operator:
const filterNumbers = numbers.reduce((currenttotal, item) => {
return (item.a ?? 0) + currenttotal;
}, 0);
Checking for falsey values of item.a (basically longer short circuit evaluation):
const filterNumbers = numbers.reduce((currenttotal, item) => {
return (item.a ? item.a : 0) + currenttotal;
}, 0);

Since not all fields have an a key the reduce does not find a value and return NAN.
The solution it`s the same as the previous answer, but i rather use immutability in variables since prevents future erros.
const numbers = [{ a: 1 }, { a: 6 }, { a: 3 }, { d: 4 }, { e: 5 }, { f: 5 }];
const filterNumbers = numbers.reduce((currenttotal, item) => {
const keys = Object.keys(item);
return item[keys[0]] + currenttotal;
}, 0);
console.log(filterNumbers);
and in the case u need to sum only with the specific key:
const filterNumbers = numbers.reduce((currenttotal, item) => {
return (item.a ?? 0) + currenttotal;
}, 0);
console.log(filterNumbers);

Not all elements have an a key. If you want to dynamically get whichever key is present, this should work:
const numbers = [{ a: 1 }, { a: 6 }, { a: 3 }, { d: 4 }, { e: 5 }, { f: 5 }];
const filterNumbers = numbers.reduce((currenttotal, item) => {
let keys = Object.keys(item);
return item[keys[0]] + currenttotal;
}, 0);
console.log(filterNumbers);

Related

Sort Array Object in Array Object javascript

how to sort highest value in this data using javascript?
data = [{a: [{num:31}, {num:10}]},{a: [{num:4}, {num:9}]},{a: [{num:5}, {num:9}]}]
Expected
data = [{a: [{num:31}]},{a: [{num:9}]},{a: [{num:9}]}]
I try like this but never happen :)
const data_sort = data.sort((a, b) => {
let abc
if (a.a.length > 0) {
abc = a.a.sort((x, y) => x.a - x.a);
}
return a - b
})
let data = [{a: [{num:31}, {num:10}]},{a: [{num:4}, {num:9}]},{a: [{num:5}, {num:9}]}]
data = data.map(item => ({a:[item.a.sort((a, b) => b.num-a.num)[0]]})).sort((a, b) => b.a[0].num-a.a[0].num)
console.log(data)
Assuming this is the correct syntax, all you need is to map every item in the array to it's largest item, then sort that.
var data = [{
a: [{num:31}, {num:10}]
}, {
a: [{num:4}, {num:9}]
}, {
a: [{num:6}, {num:11}]
}, {
a: [{num:5}, {num:9}]
}];
var result = data.map(function(item) {
return {
a: [item.a.sort(function(a,b) {
return a.num - b.num
}).reverse()[0]]
};
}).sort(function(a, b) {
return a.a[0].num - b.a[0].num
}).reverse();
console.log(result)
.as-console-wrapper {
max-height: 100% !important;
}
Map and Reduce
const data = [{ a: [{ num: 31 }, { num: 10 }] }, { a: [{ num: 4 }, { num: 9 }] }, { a: [{ num: 5 }, { num: 9 }] }];
data.map((value) => {
value.a = [
{
num: value.a.reduce((accumulatedValue, currentValue) => {
return Math.max(accumulatedValue.num, currentValue.num);
}),
},
];
return value;
});
console.log(data)

Deep comparison of objects' properties of same type

I'm trying to compare two objects of the same type. What I want to achieve at the end, is a new object with only the properties that are different.
For example:
type A = {
id: string;
col: number;
enabled: true;
obj: {
b: number;
}
}
const a: A = {
id: "ddd",
col: 4,
enabled: true,
obj: {
b: 4
}
}
const b: A = {
id: "dde",
col: 4,
enabled: true,
obj: {
b: 3
}
}
const c = () => Object.values(a).reduce((bef, aft, i) => {
const valuesB = Object.values(b);
const keyB = Object.keys(b)[i];
return valuesB[i] === aft ? { ...bef } : { keyB: valuesB[i], ...bef }
}, {})
With my logic above I was able to get a new object like:
{
"keyB": "dde"
}
It got the value right but the key wrong and also ignored the fact that the nested object property has different values. I'm a bit stuck and out of ideas.
Any help would be extremely appreciated.
About the incorrect key, you'd just have to add brackets around keyB to use the value of the variable as key: { [keyB]: valueB, ...bef }
About the missing nested object, that's a bit more complicated but here's a solution:
const diff = <T>(obj1: T, obj2: T): Partial<T> =>
Object.values(obj1).reduce((bef, aft, i) => {
const valueB = Object.values(obj2)[i];
const keyB = Object.keys(obj2)[i];
if (valueB instanceof Object) {
const delta = diff(valueB, aft);
return Object.keys(delta).length > 0 ? { [keyB]: diff(valueB, aft), ...bef } : bef;
}
return valueB === aft ? bef : { [keyB]: valueB, ...bef };
}, {});
const c = (): Partial<A> => diff(a, b);
You have to check each field of the nested object separately. That's what the recursion is for.
I also added typings to the functions. Partial<A> is a copy of A but makes all fields optional.
The result is:
{
"obj": {
"b": 4
},
"id": "dde"
}

Transform javascript array of objects

Could you please suggest any shorter code to solve following problem. I have array of objects:
const arr1=[
{ '1': { grade: 1.3, counter: 2 } },
{ '1': { grade: 2.8, counter: 2 } },
{ '2': { grade: 4.5, counter: 1 } },
{ '2': { grade: 2.4, counter: 1 } }
]
the output should look like:
const obj1={
'1': {grade:4.1,counter:4}
'2': {grade:6.9,counter:2}
}
here is the code i have tried :
arr1.reduce((acc,e)=> {
let element = Object.keys(e)
if(!acc.hasOwnProperty(element)){
acc[element]={grade:0,counter:0}
}
acc[element].grade+= e[element].grade
acc[element].counter+= e[element].counter
return acc
}, {})
Thank you
Your problem here is that Object.keys(e) return an array of keys and not a single key.
If your object will always be the same (with one key) the you can get the key with : let element = Object.keys(e)[0]
I've decomposed the code with 2 main parts.
Getting the key of the current item (with const key = Object.keys(current)[0])
Checking if the newObject has the key
If yes : updating the grade and counter value with the current object
If no : adding the current object to the key
const arr1 = [{
'1': {
grade: 1.3,
counter: 2
}
},
{
'1': {
grade: 2.8,
counter: 2
}
},
{
'2': {
grade: 4.5,
counter: 1
}
},
{
'2': {
grade: 2.4,
counter: 1
}
}
]
const newObject = arr1.reduce((newObject, current) => {
const key = Object.keys(current)[0]
const associatedObject = newObject[key]
if (associatedObject) {
associatedObject.grade += current[key].grade
associatedObject.counter += current[key].counter
} else {
newObject[key] = current[key]
}
return newObject
}, {})
console.log(newObject)
I would go for:
arr1.reduce((o,n)=>{
Object.keys(n).forEach((key)=>{
if(!o[key]) o[key]={grade:0, counter:0};
o[key]["grade"] += n[key]["grade"];
o[key]["counter"] += n[key]["counter"];
});
return o;
},{});
Step1: reducing over the array, acc = {}
Step2: iterating over every key of the object at the current index
Step3: summing up the according properties
You forgot to iterate over the keys.
Comment: As a pons asinorum I use for array.reduce() the variable names:
o meaning old value (=acc=_accumulator)
n meaning new value.
Try this
let arr1=[{'1': {grade: 1.3, counter: 2}},{'1': {grade: 2.8, counter: 2}},{'2': {grade: 4.5, counter: 1}},{'2': {grade: 2.4, counter: 1}}];
arr1 = arr1.reduce((acc, obj) => {
let [k, v] = Object.entries(obj)[0];
if(!acc.hasOwnProperty(k)) acc[k] = {grade:0,counter:0};
acc[k].grade += v.grade;
acc[k].counter += v.counter;
return acc
}, {});
console.log(arr1)
Object.keys returns an array of strings, so to check here you would probably want the first one:
arr1.reduce((acc, e) => {
const element = Object.keys(e)[0]; // `[0]` accesses the first key
if(!acc.hasOwnProperty(element)){
acc[element]={grade:0,counter:0}
}
acc[element].grade+= e[element].grade
acc[element].counter+= e[element].counter
return acc
}, {});
Then instead of the if statement you can use the new logical nullish assignment operator:
arr1.reduce((acc, e) => {
const element = Object.keys(e)[0];
acc[element] ??= { grade: 0, counter: 0 };
acc[element].grade += e[element].grade;
acc[element].counter += e[element].counter;
return acc
}, {});
This is probably as short as I'd go before it starts getting pointless.
Even further; using nullish coalescing and optional chaining:
arr1.reduce((acc, e) => {
const element = Object.keys(e)[0];
acc[element] = {
grade: (acc[element]?.grade ?? 0) + e[element].grade,
counter: (acc[element?.counter ?? 0) + e[element].counter,
};
return acc
}, {});
With Object.assign to do it all in one line:
arr1.reduce((acc, e) => {
const element = Object.keys(e)[0];
return Object.assign(acc, {
[element]: {
grade: (acc[element]?.grade ?? 0) + e[element].grade,
counter: (acc[element?.counter ?? 0) + e[element].counter,
},
});
}, {});
Finally, just for kicks, let's inline the element variable altogether to get this amazing line:
arr1.reduce((acc, e) => Object.assign(acc, {
[Object.keys(e)[0]]: {
grade: (acc[Object.keys(e)[0]]?.grade ?? 0) + e[Object.keys(e)[0]].grade,
counter: (acc[Object.keys(e)[0]]?.counter ?? 0) + e[Object.keys(e)[0]].counter,
},
}), {});
Another solution is:
const obj1 = arr1.reduce((acc, value) => {
if(acc[Object.keys(value)[0]]) {
acc[Object.keys(value)[0]].grade = acc[Object.keys(value)[0]].grade + value[Object.keys(value)[0]].grade;
acc[Object.keys(value)[0]].counter = acc[Object.keys(value)[0]].counter + value[Object.keys(value)[0]].counter;
} else {
acc[Object.keys(value)[0]] = value[Object.keys(value)[0]];
}
return acc;
})

Issue arranging values in ascending order [duplicate]

This question already has answers here:
Sort Array Elements (string with numbers), natural sort
(8 answers)
Closed 11 months ago.
I am trying to arrange given values in ascending orders
const value = [
{ val: "11-1" },
{ val: "12-1b" },
{ val: "12-1a" },
{ val: "12-700" },
{ val: "12-7" },
{ val: "12-8" },
];
I am using code below to sort this in ascending order:
value.sort((a,b)=>(a.val >b.val)? 1:((b.val>a.val)?-1:0));
The result of this sort is in the order 11-1,12-1a, 12-1b, 12-7, 12-700, 12-8. However, I want the order to be 11-1,12-1a, 12-1b, 12-7, 12-8, 12-700.
How can I achieve that?
If you're only interested of sorting by the value after the hyphen you can achieve it with this code:
const value = [
{val:'12-1'},
{val:'12-700'},
{val:'12-7'},
{val:'12-8'},
];
const sorted = value.sort((a,b) => {
const anum = parseInt(a.val.split('-')[1]);
const bnum = parseInt(b.val.split('-')[1]);
return anum - bnum;
});
console.log(sorted);
updated the answer as your question update here's the solution for this:
const value = [{ val: '11-1' }, { val: '12-1b' }, { val: '12-1a' }, { val: '12-700' }, { val: '12-7' }, { val: '12-8' }];
const sortAlphaNum = (a, b) => a.val.localeCompare(b.val, 'en', { numeric: true });
console.log(value.sort(sortAlphaNum));
You can check the length first and then do the sorting as follow:
const value = [
{ val: "12-1" },
{ val: "12-700" },
{ val: "12-7" },
{ val: "12-8" },
];
const result = value.sort(
(a, b)=> {
if (a.val.length > b.val.length) {
return 1;
}
if (a.val.length < b.val.length) {
return -1;
}
return (a.val >b.val) ? 1 : ((b.val > a.val) ? -1 : 0)
}
);
console.log(result);
little change's to #Christian answer it will sort before and after - value
const value = [{ val: '12-1' }, { val: '12-700' }, { val: '11-7' }, { val: '12-8' }];
const sorted = value.sort((a, b) => {
const anum = parseInt(a.val.replace('-', '.'));
const bnum = parseInt(b.val.replace('-', '.'));
return anum - bnum;
});
console.log(sorted);
If you want to check for different values both before and after the hyphen and include checking for letters, the solution at the end will solve this.
Here's what I did:
Created a regex to split the characters by type:
var regexValueSplit = /(\d+)([a-z]+)?-(\d+)([a-z]+)?/gi;
Created a comparison function to take numbers and letters into account:
function compareTypes(alpha, bravo) {
if (!isNaN(alpha) && !isNaN(bravo)) {
return parseInt(alpha) - parseInt(bravo);
}
return alpha > bravo;
}
Split the values based on regexValueSplit:
value.sort((a, b) => {
let valuesA = a.val.split(regexValueSplit);
let valuesB = b.val.split(regexValueSplit);
This produces results as follows (example string "12-1a"):
[
"",
"12",
null,
"1",
"a",
""
]
Then, since all the split arrays should have the same length, compare each value in a for loop:
for (let i = 0; i < valuesA.length; i++) {
if (valuesA[i] !== valuesB[i]) {
return compareTypes(valuesA[i], valuesB[i]);
}
}
// Return 0 if all values are equal
return 0;
const value = [{
val: "11-1"
},
{
val: "12-1b"
},
{
val: "12-1a"
},
{
val: "12-700"
},
{
val: "12-7"
},
{
val: "12-8"
},
];
var regexValueSplit = /(\d+)([a-z]+)?-(\d+)([a-z]+)?/gi;
function compareTypes(alpha, bravo) {
if (!isNaN(alpha) && !isNaN(bravo)) {
return parseInt(alpha) - parseInt(bravo);
}
return alpha > bravo;
}
value.sort((a, b) => {
let valuesA = a.val.split(regexValueSplit);
let valuesB = b.val.split(regexValueSplit);
for (let i = 0; i < valuesA.length; i++) {
if (valuesA[i] !== valuesB[i]) {
return compareTypes(valuesA[i], valuesB[i]);
}
}
return 0;
});
console.log(JSON.stringify(value, null, 2));
Since you are sorting on string values, try using String.localeCompare for the sorting.
Try sorting on both numeric components of the string.
const arr = [
{val:'12-1'},
{val:'11-900'},
{val:'12-700'},
{val:'12-7'},
{val:'11-1'},
{val:'12-8'},
{val:'11-90'},
];
const sorter = (a, b) => {
const [a1, a2, b1, b2] = (a.val.split(`-`)
.concat(b.val.split(`-`))).map(Number);
return a1 - b1 || a2 - b2; };
console.log(`Unsorted values:\n${
JSON.stringify(arr.map(v => v.val))}`);
console.log(`Sorted values:\n${
JSON.stringify(arr.sort(sorter).map(v => v.val))}`);

How to add elements to specific index conditionaly?

I have an array of objects and I want to add an element to specific index when a certain attribute changes compared to the previous one.
We have:
const arr = [
{ num: 1 },
{ num: 1 },
{ num: 1 },
{ num: 3 },
{ num: 3 },
{ num: 4 },
{ num: 5 },
];
I want it to become
const arr = [
{ separator:true }
{ num: 1 },
{ num: 1 },
{ num: 1 },
{ separator:true }
{ num: 3 },
{ num: 3 },
{ separator:true }
{ num: 4 },
{ separator:true }
{ num: 5 },
];
I did this:
const getIndexes = (myArr) => {
let indexes = [];
let previousValue = null;
myArr.forEach((el, idx) => {
if (el.num !== previousValue) {
indexes.push(idx);
previousValue = el.num;
}
});
return indexes;
};
const insertSeparator = (arr) => {
let result = arr;
getIndexes(arr).forEach((position) => result.splice(position, 0, { separator: true }));
return result
};
and it returns:
[
{ separator: true },
{ num: 1 },
{ num: 1 },
{ separator: true },
{ num: 1 },
{ separator: true },
{ separator: true },
{ num: 3 },
{ num: 3 },
{ num: 4 },
{ num: 5 }
]
Maybe because of the "new" size of the array, because it is getting bigger and changes its dimension.
What do you think is the best way to solve this?
Run it through .flatMap()
const result = arr.flatMap((obj, idx, arr) => {...
.flatMap() is .map() and .flat() combined, so it transforms the contents of a copy of the given array and removes the brackets []. Next, we return the first object with a separator:
if (idx == 0) {
// returns are wrapped in brackets because they'll be removed before being returned
return [{separator: true}, obj];
}
The next step is to compare the current value with the previous value:
obj.num == arr[idx - 1].num ? // current value vs previous value
[arr[idx - 1]] : // if they are the same value return previous value
[{separator: true}, obj]; /* if they are not the same then return that separator
and current */
const arr = [
{ num: 1 },
{ num: 1 },
{ num: 1 },
{ num: 3 },
{ num: 3 },
{ num: 4 },
{ num: 5 },
];
const result = arr.flatMap((obj, idx, arr) => {
if (idx == 0) {
return [{
separator: true
}, obj];
}
return obj.num == arr[idx - 1].num ? [arr[idx - 1]] : [{
separator: true
}, obj];
});
console.log(JSON.stringify(result, null, 2));
I propose this solution which would consume only one iteration with a reduce :
const arr = [{
num: 1
},
{
num: 1
},
{
num: 1
},
{
num: 3
},
{
num: 3
},
{
num: 4
},
{
num: 5
},
];
let prev_value = arr[0];
const result = arr.reduce((acc, val) => {
const insert = (val.num !== prev_value.num) ? [{
separator: true
}, val] : [val];
prev_value = val;
return acc.concat(insert)
}, [{
separator: true
}, ])
console.log(result)
There must be other ways to do it too. But with a simple modification to your code it can be done. You just need to keep track of the offset with a new variable, incrementing it in the loop:
const arr = [
{ num: 1 },
{ num: 1 },
{ num: 1 },
{ num: 3 },
{ num: 3 },
{ num: 4 },
{ num: 5 },
];
const getIndexes = (myArr) => {
let indexes = [];
let previousValue = null;
myArr.forEach((el, idx) => {
if (el.num !== previousValue) {
indexes.push(idx);
previousValue = el.num;
}
});
return indexes;
};
const insertSeparator = (arr) => {
let result = [...arr];
let offset = -1;
getIndexes(arr).forEach((position) => {
offset++;
return result.splice(position+offset, 0, { separator: true });
});
return result
};
console.log(insertSeparator(arr));
Note: If you want to start with 0 you can do the increment in the .splice() itself : result.splice(position+(offset++),
const positions = [];
//arr.sort((a, b) => a.num - b.num); You can uncomment this line to ensure that the array will always sorted based on num property
arr.forEach((item, index) => {
if (index < arr.length - 1 && item.num != arr[index + 1].num) {
positions.push(index + 1);
}
});
let counter = 0;
positions.forEach((pos) => {
arr.splice(pos + counter++, 0, { separator: true });
});
console.log(arr);
You want to:
Do something which each item in a list
Want to return something other than a list of the same size.
Then I would suggest the good all-round Array.prototype.reduce() function.
const separator = {separator: true};
arr.reduce((result, item) => {
if (result.at(-1)?.num === item.num) {
return [...result, separator, item];
}
return [...result, item]
}, [])
This is (according to me) easier, cleaner and safer since it doesn't mutate variables.
Note
Array.prototype.at() is at the time of writing a new function. If you are using an ancient browser that doesn't support it you can use arr[arr.length -1] to get the last item instead.

Categories