Answers for "sort array node js"

25

JS array sort

numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
Posted by: Guest on May-08-2021
1

array sort js

arr = ['width', 'score', done', 'neither' ]
arr.sort() // results to ["done", "neither", "score", "width"]

arr.sort((a,b) => a.localeCompare(b)) 
// if a-b (based on their unicode values) produces a negative value, 
// a comes before b, the reverse if positive, and as is if zero

//When you sort an array with .sort(), it assumes that you are sorting strings
//. When sorting numbers, the default behavior will not sort them properly.
arr = [21, 7, 5.6, 102, 79]
arr.sort((a, b) => a - b) // results to [5.6, 7, 21, 79, 102]
// b - a will give you the reverse order of the sorted items 

//this explnation in not mine
Posted by: Guest on October-07-2020
-2

sort array

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.sort();
Posted by: Guest on June-10-2021
-2

js sort an array

// sort an array
// by drinks: lowest to highest
function sortDrinkByPrice(drinks) {
	return drinks.sort((a, b) => {
		return a.price - b.price;
	});
}

// parse the array as parameters within the function
console.log(sortDrinkByPrice([{name: "lemonade", price: 50},{name: "lime", price: 10}]));
Posted by: Guest on March-12-2021

Browse Popular Code Answers by Language