This question already has answers here:
How to sort 2 dimensional array by column value?
(14 answers)
Closed 6 years ago.
I need to sort an complex array order by one column of the array.
For example, this array might looks like
array = [["Banana","Chapter3"], ["Orange","Chapter2"], ["Apple","Chapter1"]];
I want it to sort by Chapter, so the result will be
array = ["Apple","Chapter1"],["Orange","Chapter2"],["Banana","Chapter3"]]
But if I do array.sort, it will become
[["Apple","Chapter1"],["Banana","Chapter3"],["Orange","Chapter2"]]
It seems sort by first element's ascii code. How do I sort by specific element in array?
I also created a JSfiddle to illustrate my idea.
You need to pass a comparator to sort:
var array = [["Banana","Chapter3"], ["Orange","Chapter2"], ["Apple","Chapter1"]];
var sorted = array.sort(function (a, b) {
if (a[1] > b[1]) {
return 1;
} else if (a[1] < b[1]) {
return -1;
} else {
return 0;
}
});
console.log(sorted);
// [ [ 'Apple', 'Chapter1' ],
// [ 'Orange', 'Chapter2' ],
// [ 'Banana', 'Chapter3' ] ]
Related
This question already has answers here:
Fastest way to move first element to the end of an Array
(9 answers)
How to get the first element of an array?
(35 answers)
Closed 5 months ago.
I have an array which I have sorted from smallest integer to largest. The array data comes from backend and will be random numbers
// example array from backend
const arr = [400,30,10,-1]
const sortedArray = arr.sort((a, b) => a - b)
// [-1,10,30,400]
If the first index of the array is equal to -1 I want to remove it from the first position in the array and append it to the last position of the array.
For example if array is [-1, 10, 30, 400] I want to return [10,30,400,-1].
Edit: I am looking for the safest possible way and unsure to use splice(), filter() etc
shift the first element off the array and push it on the end.
const arr = [400,30,10,-1].sort();
if (arr[0] === -1) arr.push(arr.shift());
console.log(arr);
After your code you can check first element is -1 and then slice and push -1 to it
if(arr[0] == -1){
arr = arr.slice(1)
arr.push(-1)
}
I might have exaggerated the solution, but I am guessing it might help someone.
const beData = [400, 30, 10, -1];
const sortedData = beData.sort((a, b) => a - b);
const newArr = sortedData.reduce((prevValue, currValue) => {
if(currValue < 0) {
prevValue[1].push(currValue);
} else {
prevValue[0].push(currValue);
}
return prevValue;
}, [[], []]);
const result = [...newArr[0], ...newArr[1]];
console.log(result);
This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Sort array of objects by string property value
(57 answers)
Closed 2 years ago.
I have an array of objects like the one below. Although, the order isn't in ascending or descending. Is there function that sorts the numbers in each object and replacing it into a new array or something similar?
let array = [
{
number: 16
},
{
number: 25
},
{
number: 20
},
{
number: 28
}
];
Yes, you can use array.sort() on a copy of your array.
example:
let newArray = [...array].sort((a, b) => a.number - b.number)
That will sort your array ascending.
If you want it descending just switch to b.number - a.number
More info on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
This question already has answers here:
How to sort 2 dimensional array by column value?
(14 answers)
Closed 2 years ago.
I have an array like this:
let pairs = [[2,"test"], [7,"buzz"], [3,"asd"]]
How can i sort the outer array by the first values? (descending)
Pass a compare function to Array.sort that examines the first element in each array, to determine the required order.
> let pairs = [[2,"test"], [7,"buzz"], [3,"asd"]]
> pairs.sort((a, b) => a[0] - b[0]);
[ [ 2, 'test' ], [ 3, 'asd' ], [ 7, 'buzz' ] ]
This question already has answers here:
Sorting object property by values
(44 answers)
Closed 4 years ago.
I have an array and I need to sort it in desc order, but it doesn't seem to work. What could I fix?
var array = [];
array['a'] = ['1','2','3'];
array['b'] = ['2','3'];
array['c'] = ['5','6','8','9'];
array.sort(function(a, b) {
return a.length < b.length ? -1 : (a.length > b.length ? 1 : 0);
});
console.log(array);
What could I fix?
Your array is empty, as it doesn't have numeric keys. Therefore sorting it does nothing, when logging you see the non-numeric keys in the array.
As you want fast lookup you need a hashtable (object or Map) however, they are not sorted, so you also need an array to have a sorted order. You could easily build both for your data:
const lookup = {
a: [ '1','2','3'],
b: ['2','3'],
c: ['5','6','8','9'],
};
const sorted = Object.values(lookup).sort((a, b) => a.length - b.length);
console.log(
lookup["a"],
sorted[0]
);
This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Closed 6 years ago.
If i have an array:
myArray = [['0','Mouse'],['1','Dog'],['2','Cat'],['3','Gerbil']];
How can I alphabetize the array based on the, in this case, animals?
myArray = alpha(myArray);
Results:
myArray = [['2','Cat'],['1','Dog'],['3','Gerbil'],['0','Mouse']];
you can use sort function
var myArray = [['0','Mouse'],['1','Dog'],['2','Cat'],['3','Gerbil']];
console.log(alpha(myArray));
var arr2 = [['5','Mouse'],['0','Mouse'],['1','Dog'],['2','Cat'],['3','Gerbil']];
console.log('another array', alpha(arr2));
function alpha(arr) {
return arr.sort((a, b) => a[1] > b[1]);
}
You could use Array#sort
The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.
in combination with String#localeCompare
The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
var array = [['5', 'Mouse'], ['0', 'Mouse'], ['1', 'Dog'], ['2', 'Cat'], ['3', 'Gerbil']];
array.sort(function (a, b) {
return a[1].localeCompare(b[1]);
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }