“Bagaimana cara menyortir array” Kode Jawaban

JavaScript orderby

var items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort(function (a, b) {
  return a.value - b.value;
});

// sort by name
items.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});
Clever Crocodile

Urutkan array di JavaScript

var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
  return a - b;
});

console.log(numArray);
 Run code snippet
Cooperative Cobra

Java mengurutkan array int

// an array of ints
int[] arr = {1, 2, 3, 4, 5, 6};

// an array of reverse sorted ints
int[] arrDesc = Arrays.stream(arr).boxed()
    .sorted(Collections.reverseOrder())
    .mapToInt(Integer::intValue)
    .toArray();

System.out.println(Arrays.toString(arrDesc)); // outputs [6, 5, 4, 3, 2, 1]
Difficult Donkey

JavaScript menyortir array

sorting an array
Foolish Fish

Bagaimana cara menyortir array

var carBrands = ["Toyota", "Jeep", "Ford", "Volvo"];
carBrands.sort();
// array.sort() method sorts an array in ascending order by default
// extend the function like below to sort in descending order or customize
//carBrands.sort(function(a, b){return b-a});
handOfCode

Urutkan array

// C++ code for k largest elements in an array
#include <bits/stdc++.h>
using namespace std;
  
void kLargest(int arr[], int n, int k)
{
    // Sort the given array arr in reverse
    // order.
    sort(arr, arr + n, greater<int>());
  
    // Print the first kth largest elements
    for (int i = 0; i < k; i++)
        cout << arr[i] << " ";
}
  
// driver program
int main()
{
    int arr[] = { 1, 23, 12, 9, 30, 2, 50 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
    kLargest(arr, n, k);
}
  
// This article is contributed by Chhavi
Lucky Lobster

Jawaban yang mirip dengan “Bagaimana cara menyortir array”

Pertanyaan yang mirip dengan “Bagaimana cara menyortir array”

Lebih banyak jawaban terkait untuk “Bagaimana cara menyortir array” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya