How to call a reduce function in another function - javascript

I am trying to call this reduce function:
users.reduce(function (acc, obj) { return acc + obj.age/3; }, 0);
in this function:
function computeUserAverageAge(users) {};
to test this array of objects for the average of these "age" values:
const users = [{
name: 'Brendan Eich',
age: 56,
}, {
name: 'Linus Torvalds',
age: 48,
}, {
name: 'Margaret Hamilton',
age: 81,
}];
I am thankful for your help and patience!

Just move it with in the function and return the result.
Note: instead of using 3 use users.length instead.
I also think that mathematically, you should divide by the number after you add them up, and not each iteration.
const users = [{
name: 'Brendan Eich',
age: 56,
}, {
name: 'Linus Torvalds',
age: 48,
}, {
name: 'Margaret Hamilton',
age: 81,
}];
function computeUserAverageAge(users) {
return Math.round(users.reduce((acc, obj) => acc + obj.age, 0) / users.length);
};
console.log(computeUserAverageAge(users))

Sounds like you just need to return the result of the reduce. Might as well use arrow functions for brevity:
const computeUserAverageAge = users => users.reduce((a, { age }) => a + age, 0) / 3;
console.log(computeUserAverageAge(
[{
name: 'Brendan Eich',
age: 56,
}, {
name: 'Linus Torvalds',
age: 48,
}, {
name: 'Margaret Hamilton',
age: 81,
}]
));

Related

Copy values from multiple keys from array of object

I want to copy value of name and age into another array, below code is working fine, But I wanted to know better way to do it.
const users = [
{ id: 0, name: 'John', age:34 },
{ id: 1, name: 'Wayne', age:44 },
{ id: 2, name: 'David', age:24 },
];
let values=[];
users && users.map(user => {
values.push(user['name'])
values.push(user['age'])
})
console.log(values);
output
['John', 34, 'Wayne', 44, 'David', 24]
You can bind each items to an array containing both its name and age and then flattern these arrays.
This can be done using Array#FlatMap
const users = [
{ id: 0, name: 'John', age:34 },
{ id: 1, name: 'Wayne', age:44 },
{ id: 2, name: 'David', age:24 },
];
const nameAndAges = users.flatMap(user => [user.name, user.age])
console.log(nameAndAges)
Your solution looks good, this can be also solved in different ways, I guess you may want to create function for handling this.
const users = [
{ id: 0, name: 'John', age: 34 },
{ id: 1, name: 'Wayne', age: 44 },
{ id: 2, name: 'David', age: 24 },
];
const result = mapArrayToProps(users, ['name', 'age']);
function mapArrayToProps(arr, props) {
return arr.flatMap(obj => mapObjectToProps(obj, props));
}
function mapObjectToProps(obj, props) {
return props.map(prop => obj[prop])
}
console.log(result);

Compare 2 two different arrays and show the object with the same value with js

I need to find if values inside two different arrays of objects is equal. This is an example of what i need:
https://jsfiddle.net/5cb1xsq2/10/
I need to compare the object1 and object2 arrays, and show only the object1 array with the same 'years' value of the object2 array.
This is the result for this case:
{
'name': 'john',
'surname': 'doe',
'years': 29
}
Thank you!
var array1 = [
{
name: "john",
surname: "doe",
years: 29,
},
{
name: "tiler",
surname: "phillis",
years: 50,
},
{
name: "mathias",
surname: "terry",
years: 45,
},
];
var array2 = [
{
name: "mary",
surname: "poppins",
years: 32,
},
{
name: "mickey",
surname: "mouse",
years: 29,
},
{
name: "minnye",
surname: "mouse",
years: 36,
},
];
var results = array1.filter(parentObj => array2.filter(childObj => childObj.years == parentObj.years).length > 0);
If there is only one match, then something like this?
let result;
for (let i = 0; i < array2.length; i += 1) {
const a2 = array2[i]
const index = array1.findIndex((a1) => a1.years === a2.years);
if (index > -1) {
result = array1[index];
break;
}
}
You can filter the first array using the result of filtering the second array with each element comparison.
var array1 = [
{ years: 29 },
{ years: 50 },
{ years: 60 }
];
var array2 = [
{ years: 29 },
{ years: 30 },
{ years: 50 }
];
console.log(array1.filter(x => array2.filter(y => y.years == x.years).length > 0));

How to add property to json file with map function?

Hello I m trying to map through a json file and add a new property to every object in it.
DATA.JSON
const arr = [
{
index: 0,
name: "John",
hair: "Brown",
},
{
index: 1,
name: "Bob",
hair: "Blonde",
},
];
APP.JS
const data = require("./data.json");
const items = data.map((item) => {
return ????
});
I want to map through the array, and add a "age" property to every index with a value of 30 or even just an empty value would be ok. with result something like this:
RESULT
const a =
[
{
index: 0,
name: "John",
hair: "Brown",
age: 30
},
{
index: 1,
name: "Bob",
hair: "Blonde",
age: 30
},
];
const arr = [
{
index: 0,
name: "John",
hair: "Brown",
},
{
index: 1,
name: "Bob",
hair: "Blonde",
},
];
const result = arr.map((obj) => {
return { ...obj, age: 30 };
});
console.log(result);
You can also make it one-liner
const result = arr.map((obj) => ({ ...obj, age: 30 }));
If you want to print only hair of each index then
const arr = [
{
index: 0,
name: "John",
hair: "Brown",
},
{
index: 1,
name: "Bob",
hair: "Blonde",
},
];
const result = arr.map((obj) => {
return { ...obj, age: 30 };
});
const hairs = result.map((o) => o.hair);
console.log(hairs); // Printing as an array
console.log(hairs.toString()); // Printing as comma separated value
Hello you could do something like this:
const data = [
{
index:0,
name: "John",
hair: "Brown",
},
{
index:1,
name: "Bob",
hair: "Blonde",
},
];
const newData = data.map(item => ({
...item,
newProp: 'hello world',
}));
// Print whole data:
console.log(newData);
// Filter specific properties
const hair = newData.map(item => item['hair'])
console.log('only hair ->', hair);
Side note, you don't need the index property in the object since you can get it while looping.
map(currentItem, index) Docs
If you want to print specific properties of the object you can do as such:
console.log(newData.map(item => item['hair']));

The output of the below code is NaN, Why? [duplicate]

This question already has answers here:
Calling reduce to sum array of objects returns NaN
(2 answers)
Closed 3 years ago.
Here, i am trying to add 'order_total' property. I have used reduce method, if try for only arrays, the same code is working properly, but when i implemented on array of objects it is resulting NaN.
var user = {
id: 16,
username: 'smith',
email: 'smith#gmail.com',
order: [
{
id: 71,
order_number: 'DCT-123',
order_total: 12000,
},
{
id: 71,
order_number: 'DCT-345',
order_total: 7000,
},
{
id: 71,
order_number: 'DCT-321',
order_total: 2000,
}
]
};
var result = user.order.reduce(function(a, b) {
return a.order_total + b.order_total;
});
console.log(result);
The parameter a in the reduce callback is the accumulator, not the property of the object. Refer here to learn more about reduce
var user = {
id: 16,
username: 'smith',
email: 'smith#gmail.com',
order: [
{
id: 71,
order_number: 'DCT-123',
order_total: 12000,
},
{
id: 71,
order_number: 'DCT-345',
order_total: 7000,
},
{
id: 71,
order_number: 'DCT-321',
order_total: 2000,
}
]
};
var result = user.order.reduce(function(a, b) {
return a+b.order_total;
},0);
console.log(result);
You return a number, not an object.
var result = user.order.reduce(function(a, b) {
// ^ object
// ^ object
return a.order_total + b.order_total; // number
});
You need a start value of zero and add the value of the property.
var user = {
id: 16,
username: 'smith',
email: 'smith#gmail.com',
order: [
{
id: 71,
order_number: 'DCT-123',
order_total: 12000,
},
{
id: 71,
order_number: 'DCT-345',
order_total: 7000,
},
{
id: 71,
order_number: 'DCT-321',
order_total: 2000,
}
]
};
var result = user.order.reduce(function(total, a) {
return total + a.order_total;
}, 0);
console.log(result);

How to calculate the average in JavaScript of the given properties in the array of objects

I have an array of objects. Each object contains a few properties and one of these properties is age.
var people = [
{
name: 'Anna',
age: 22
},
{
name: 'Tom',
age: 34
}, {
name: 'John',
age: 12
},
]
I want to calculate the average for all the age properties in this array. I use this function:
let getAverage = arr => {
let reducer = (total, currentValue) => total + currentValue;
let sum = arr.reduce(reducer)
return sum / arr.length;
}
It works fine for the simple array like [22, 34, 12] but it does not for the arrays of objects.
How to modify my getAverage function to make it works also with arrays of object?
Here is the snippet with my code:
https://jsfiddle.net/marektchas/kc8Ls0f5/2/
You don't need to modify getAverage - you can pre-process the array before handing it off, in which case getAverage will work exactly as needed:
var people = [
{
name: 'Anna',
age: 22
},
{
name: 'Tom',
age: 34
}, {
name: 'John',
age: 12
},
]
let getAverage = arr => {
let reducer = (total, currentValue) => total + currentValue;
let sum = arr.reduce(reducer)
return sum / arr.length;
}
let ages = people.map(person => person.age);
console.log(getAverage(ages));
If you want to change getAverage, so it can handle any potential type of input, then you can add an optional argument that will perform value extraction, so you don't have to run a map on each array.
var numbers = [
1,
2,
3,
4,
5
]
var people = [
{
name: 'Anna',
age: 22
},
{
name: 'Tom',
age: 34
}, {
name: 'John',
age: 12
},
]
var moreComplexObjects = [
{
a: {
b: {
c: 6
}
}
},
{
a: {
b: {
c: 7
}
}
},
{
a: {
b: {
c: 8
}
}
}
]
//the default value of the second parameter is a function that returns the input
let getAverage = (arr, valueExtractor = x => x) => {
//extract the value of each element
let reducer = (total, currentValue) => total + valueExtractor(currentValue);
let sum = arr.reduce(reducer, 0) //make sure you add an initialiser
return sum / arr.length;
}
const ageExtractor = person => person.age;
const complexKeyExtractor = obj => obj.a.b.c;
console.log(getAverage(numbers));
console.log(getAverage(people, ageExtractor));
console.log(getAverage(moreComplexObjects, complexKeyExtractor));
A note for the above, if you don't supply a second parameter to Array#reduce, then the first time it runs total will be the first element of the array, however the second time and onwards, it will be the sum so far. It's not worth handling that case, so supplying an initial value solves it.
You can use reduce() and add property age of each object in array to ac. Don't forget to pass 0(initial value of ac) as second argument otherwise it would return NaN
var people = [
{
name: 'Anna',
age: 22
},
{
name: 'Tom',
age: 34
}, {
name: 'John',
age: 12
},
]
let avgs = people.reduce((ac,a) => a.age + ac,0)/people.length
console.log(avgs)
You could supply a function for the wanted property and reduce with a start value.
const
getAverage = (array, fn = v => v) => {
var reducer = fn => (total, item) => total + fn(item),
sum = array.reduce(reducer(fn), 0);
return sum / array.length;
};
var people = [{ name: 'Anna', age: 22 }, { name: 'Tom', age: 34 }, { name: 'John', age: 12 }];
console.log(getAverage(people, o => o.age));
We can use Array.reduce to compute the sum, where acc is the accumulated sum and the individual objects are destructured to the age variable then calculate the average by dividing the sum with the array length:
var people = [
{
name: 'Anna',
age: 22
},
{
name: 'Tom',
age: 34
}, {
name: 'John',
age: 12
},
];
function getAvg(arr){
return (people.reduce((acc, {age}) => (acc + age), 0))/arr.length;
}
console.log(getAvg(people));
We can also map the function to the age property and calculate the sum by joining the array into a string and evaluating it inside the Function constructor:
var people = [
{
name: 'Anna',
age: 22
},
{
name: 'Tom',
age: 34
}, {
name: 'John',
age: 12
},
];
function getAvg(arr){
return (new Function(`return ${people.map(({age}) => age).join("+")}`)()) / arr.length;
}
console.log(getAvg(people));
More Simplified code
just execute as getAverage(people.map(p=> p.age)); using your code
var people = [
{
name: 'Anna',
age: 22
},
{
name: 'Tom',
age: 34
}, {
name: 'John',
age: 12
},
];
let getAverage = arr => {
let reducer = (total, currentValue) => total + currentValue;
let sum = arr.reduce(reducer)
return sum / arr.length;
};
console.log(getAverage(people.map(p=> p.age)));

Categories

Resources