Javascript Reduce for object [duplicate] - javascript

This question already has answers here:
Calling reduce to sum array of objects returns NaN
(2 answers)
js - array .reduce returns NaN instead of calculated value [duplicate]
(2 answers)
Method reduce javascript [duplicate]
(3 answers)
reduce() method is returning NaN from an array of objects [duplicate]
(1 answer)
Closed last month.
const obj = [
{
name: "john",
marks: 50,
},
{
name: "mary",
marks: 55,
},
{
name: "peter",
marks: 75,
},
];
I want to calculate sum of marks using reduce method.
I tried through this way -
const sum = obj.reduce((next, number) => {
console.log("next", next.marks);
console.log("number", number.marks);
return next.marks + number.marks;
});
console.log(sum);
But I am getting sum as NaN and overall result as -
next 50
number 55
next undefined
number 75
NaN
I am not sure why next is getting undefined in between.
How can I calculate sum through reduce method ?

Pass a default value to reduce as 0
const obj=[{ name: "john", marks: 50 }, { name: "mary", marks: 55 }, { name: "peter", marks: 75 } ];
const sum = obj.reduce((acc, number) => {
return acc+ number.marks;
}, 0);
console.log(sum)

Related

Sort Object Javascript by Number [duplicate]

This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Sorting arrays numerically by object property value
(10 answers)
Closed 21 days ago.
var object = [
{ name: 'Mar', age: 32 ,height:40},
{ name: 'Carla', age: 10 ,height:15},
{ name: 'Hazel', age: 5 ,height:80}
];
Is it possible to sort based on the age element and generate a new sorted object?
Expected result:
var newobject = [
{ name: 'Hazel', age: 5 ,height:80},
{ name: 'Carla', age: 10 ,height:15},
{ name: 'Mar', age: 32 ,height:40}
];
Or you could also return the result sorted in an array, instead of returning it in an object... whatever... uncomplicated, but return it sorted .
var new_sorted_array = [
[Hazel, 5 ,80] ,
[Carla, 10 ,15],
[Mar, 32 ,40]
];
To achieve expected result, you can try below two options
Using array sort method - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Second option is by looping array and using Object.values to get output in the format specified in question
var object = [
{ name: 'Mar', age: 32 ,height:40},
{ name: 'Carla', age: 10 ,height:15},
{ name: 'Hazel', age: 5 ,height:80}
];
//Sort array by property age
console.log("Sort by age", object.sort((a, b) => a.age - b.age))
//Using object values
console.log("Sort by age -option2", object.map(v => Object.values(v)).sort((a, b) => a[1] - b[1]))

Trying to apply filter and reduce on an array to sum only numbers

I'm trying to write a function that will be called with an array that has information on a person such as their name and then age. I need this function to grab all of the numbers only and then return them then add them all together but I'm having trouble figuring out how to combine filter and reduce (if that's what I even need to use to do this in the easiest way?) so if you could help with that I would be thankful.
Maybe it would be easier for me not to use an arrow function but I just learned about them an hour ago and wanted to try them out.
Apologies for any typos/wrong jargon as my dyslexia gets the better of me sometimes.
What I've got so far;
const totalNums = arr => arr.reduce((a,b) => a + b, 0)
An example of what I want it to return when the function is supplied with the array is
{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 },
// returns 92
EDIT
Why isn't the array I'm calling this function with working? Can you provide me a working example without the array being hardcoded like the other answers? - I'm passing in an array to the function. The main objective is to grab any number from the passed in array and add them together with an empty array returning 0.
function totalNums(person) {
person.reduce((a,b) => a + b, 0)
return person.age;
}
console.log(totalNums([]))
The first argument in a reduce callback is the "accumulator" - something that takes the initial value and is then passed into each iteration. The second value is the item that's next in the iteration whether that's a number, a string, an object etc.
In your example you're iterating over an array of objects, so you must perform the sum operation using the age value of each of those objects.
const arr = [
{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 }
];
const total = arr.reduce((acc, obj) => {
return acc + obj.age;
}, 0);
console.log(total);
You can reduce the object array number as below
const objArr = [
{ name: "Clarie", age: 22 },
{ name: "Bobby", age: 30 },
{ name: "Antonio", age: 40 },
];
console.log(objArr.reduce((prev, curr) => prev + curr.age, 0));
If you want to convert the array of object into array containing only ages:
const objArr = [
{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 },
];
console.log(objArr.map(obj => obj.age));

Sort array by name with sort() [duplicate]

This question already has answers here:
Sort array by firstname (alphabetically) in JavaScript [duplicate]
(23 answers)
Closed 1 year ago.
I am trying to sort an array by names in alphabetic order, with numbers it works, but with names doesn't. Why?
var arr = [{
name: 'Thomas',
age: 19
},
{
name: 'NoƩ',
age: 17
},
{
name: 'Andrey',
age: 27
},
{
name: 'Luc',
age: 20
}
]
const res = arr.sort((e1, e2) => e1.name - e2.name)
console.log(res)
Strings may not be subtracted, but you can compare them using localeCompare
const res = arr.sort((e1, e2) =>
e1.name.toLowerCase().localeCompare(e2.name.toLowerCase())
);

Filtering specific values on json array and create another array [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.
How can i create another array by filtering one json array and include just the values pairs of a specific key?
Example (Filtering Value Pairs of Number Keys):
Array:
{ Name: 'abcd', Number: '1234' },
{ Name: 'efgh', Number: '5678' }
]````
Result Array:
````var filteredarray = ['1234','5678'];````
Thanks!
const a = [
{ Name: 'abcd', Number: '1234' },
{ Name: 'efgh', Number: '5678' }
]
function getNumbers(){
return a.map(item => item.Number);
}
getNumbers();

Given two arrays, find the item in array A with unique values in array B [duplicate]

This question already has answers here:
Filter array of objects based on another array in javascript
(10 answers)
Filter the original array of objects by array of ids
(2 answers)
Closed 3 years ago.
I've two arrays and one of them is too large. And the other one's max length is 9. What I tried to achieve is, I want to find items in the larger array by giving small array's items.
I did something like that;
const largeArray = [
{ id: 23 },
{ id: 12 },
{ id: 43 },
{ id: 54 },
{ id: 15 },
//and so on and all ids are unique
]
const smallArray = [23, 12, 43]
smallArray.map(smallArrayItem => {
largeArray.map(largeArrayItem => {
if (smallArrayItem === largeArrayItem.id) {
console.log(largeArrayItem)
}
})
})
But IMO that is not an efficient way. It's very slow. It takes almost 2 seconds to find the items. How do I make faster this search in a proper way?
Please use filter and includes
const largeArray = [
{ id: 23 },
{ id: 12 },
{ id: 43 },
{ id: 54 },
{ id: 15 },
]
const smallArray = [23, 12, 43]
const diff = largeArray.filter(item => !smallArray.includes(item.id));
console.log(diff);

Categories

Resources