javascript sort array strings alphabetically
//sort array alphabetically
objArray.sort(function(a, b) {
return a.localeCompare(b);
});
javascript sort array strings alphabetically
//sort array alphabetically
objArray.sort(function(a, b) {
return a.localeCompare(b);
});
javascript sort
var names = ["Peter", "Emma", "Jack", "Mia", "Eric"];
names.sort(); // ["Emma", "Eric", "Jack", "Mia", "Peter"]
var objs = [
{name: "Peter", age: 35},
{name: "Emma", age: 21},
{name: "Jack", age: 53}
];
objs.sort(function(a, b) {
return a.age - b.age;
}); // Sort by age (lowest first)
sorting in js
var arr = [23, 34343, 1, 5, 90, 9]
//using forEach
var sortedArr = [];
arr.forEach(x => {
if (sortedArr.length == 0)
sortedArr.push(x)
else {
if (sortedArr[0] > x) sortedArr.unshift(x)
else if (sortedArr[sortedArr.length - 1] < x) sortedArr.push(x)
else sortedArr.splice(sortedArr.filter(y => y < x).length, 0, x)
}
})
console.log(sortedArr);
// using sort method
console.log(arr.sort((a,b)=>{
return a-b;
}));
sort function
var vehicules= [
{ nom: "Peugeot 208 1,2l PureTech", img:"208.png" , co2:108 },
{ nom: "Peugeot 5008 2.0 BlueHDi 150", img:"5008.png" , co2: 118 },
{ nom: "Golf GTI", img:"golfgti.png" , co2:148 },
{ nom: "Renault Clio 0.9 TCe 90", img:"clio.jpg" , co2:114 },
{ nom: "Audi A4 2.0 TDI 190", img:"a4.png" , co2: 111},
{ nom: "BMW Serie 2 Tourer 220d", img:"serie2tourer.png" , co2:124 },
{ nom: "Audi SQ7", img:"sq7.png" , co2:198 },
{ nom: "Audi TTS", img:"tts.png" , co2:159 },
];
vehicules.sort(function (a, b) {
return a.co2 - b.co2;
});
vehicules.forEach(function(v) {
console.log(v.nom+" avec "+v.co2+" g de CO2/km");
});
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us