Sort Object Javascript by Number [duplicate] - javascript

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]))

Related

Javascript Reduce for object [duplicate]

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)

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();

Check if object has particular property [duplicate]

This question already has answers here:
Get JavaScript object from array of objects by value of property [duplicate]
(17 answers)
Find object by id in an array of JavaScript objects
(36 answers)
Closed 5 years ago.
Let's say I have an array of objects
const arr = [ {name:"Bob", age: 20}, { name: "Sara", age: 22}, { name:
Tom, age:20} ];
I want to print objects with particular property, for example only those with the age == 20. So The result would be
const arr = [ {name:"Bob", age: 20}, { name: Tom, age:20} ];
I really want to do it with ES6. Do you have any suggestion what method could be used?
This will do
var filteredData = arr.filter((e) => e.age === 20)

Categories

Resources