Answers for "how to sort in js"

14

sorting array from highest to lowest javascript

// Sort an array of numbers 
let numbers = [5, 13, 1, 44, 32, 15, 500]

// Lowest to highest
let lowestToHighest = numbers.sort((a, b) => a - b);
//Output: [1,5,13,15,32,44,500]

//Highest to lowest
let highestToLowest = numbers.sort((a, b) => b-a);
//Output: [500,44,32,15,13,5,1]
Posted by: Guest on March-25-2020
13

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)
Posted by: Guest on May-21-2020
2

javascript sort function

var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)
Posted by: Guest on May-08-2020
0

sort array javascript

let array = ['12'. '54'];
array.sort((a,b) => a -b);
Posted by: Guest on September-05-2021
1

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;
}));
Posted by: Guest on February-25-2021
0

how to sort an array

import java.util.Scanner;
public class JavaExample 
{
    public static void main(String[] args) 
    {
    	int count, temp;
    	
    	//User inputs the array size
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter number of elements you want in the array: ");
        count = scan.nextInt();
    
        int num[] = new int[count];
        System.out.println("Enter array elements:");
        for (int i = 0; i < count; i++) 
        {
            num[i] = scan.nextInt();
        }
        scan.close();
        for (int i = 0; i < count; i++) 
        {
            for (int j = i + 1; j < count; j++) { 
                if (num[i] > num[j]) 
                {
                    temp = num[i];
                    num[i] = num[j];
                    num[j] = temp;
                }
            }
        }
        System.out.print("Array Elements in Ascending Order: ");
        for (int i = 0; i < count - 1; i++) 
        {
            System.out.print(num[i] + ", ");
        }
        System.out.print(num[count - 1]);
    }
}
Posted by: Guest on October-13-2020

Browse Popular Code Answers by Language