I have the following array.
var arr = ["1-5", "3-6", "2-4"];
Is there a way where I can sort like this:
var arr = ["1-5", "2-4", "3-6"]
I've tried with jquery map but cant because the values of array are not Numbers.
You can use sort function
Sort by first number
arr.sort(function (a, b) {
// a.split('-') - split a string into an array - ['1', '5']
// a.split('-')[0] - get first element - '1'
// "+" converts string to number - 1
// the same for "b"
return +a.split('-')[0] - +b.split('-')[0];
});
Example
Sort by second number
arr.sort(function (a, b) {
return +a.split('-')[1] - +b.split('-')[1];
});
Example
Use array sort. First the first num is compared. If they are equal, the second num is compared..
var arr = ["1-5", "3-6", "2-4"];
var sorted = arr.sort(function(a,b){
var numsA = a.split('-');
var numsB = b.split('-');
if (numsA[0]-numsB[0] !== 0){
return numsA[0] - numsB[0];
}
return numsA[1] - numsB[1];
});
document.write(sorted);
You can try the built in sort functionality arr.sort()
http://jsfiddle.net/qctg9cfx/
If sorting by the first number in the string, and also if the first number could itself be negative then a more robust solution may be to use parseInt.
var arr = ["1-5", "3-6", "-1-3", "2-4"];
arr.sort(function (a, b) {
return parseInt(a, 10) - parseInt(b, 10);
});
document.body.appendChild(document.createTextNode(JSON.stringify(arr)));
Related
I have an array that looks like this
var testArray = ['name1:13', 'name2:15', 'name3:13'];
I would like to sort the array by the number to the right of the colon.
So far I have this:
var converted = testArray.map(
function (item) {
return item.split(':').map(
function (num) {
return parseInt(num);
});
})
alert(converted)
var sorted = converted.sort(function (a, b) { return a[1] - b[1] })
alert(sorted);
That sorts them in the correct order but I'm not sure how to pass over the first part of each string, the part to the left of the colon.
Right now it returns: NAN,13,NAN,13,NAN,15
Make a helper function to access the [1]st index of the split result, then in the sort callback, call that function for both and return the difference:
var testArray = ['name1:13', 'name2:15', 'name3:13'];
const getVal = str => str.split(':')[1];
testArray.sort((a, b) => getVal(a) - getVal(b));
console.log(testArray);
Split, convert to number and compare.
var testArray = ["name1:13", "name2:15", "name3:13"];
const sortFunction = (a, b) => {
const value = str => Number(str.split(":")[1]);
return value(a) - value(b);
};
testArray.sort(sortFunction);
console.log(testArray);
var testArray = ['name1:13', 'name2:15', 'name3:13'];
console.log(testArray.sort((a, b) => (a.split(":")[1] > b.split(":")[1]) ? 1 : -1))
This question already has answers here:
Natural sort of alphanumerical strings in JavaScript
(6 answers)
Closed 4 years ago.
I have this array
const arr = ['1','2','3',...'30','31','LAST']
I need to sort by number ASC
Here is the example code and I don't know how to sort it.
help me please
const arr2 = ['2','1','10','LAST','20']
I need result ['1','2','10','20','LAST'] instead of ['1','10','2','20','LAST']
You could check for NaN and move that value to bottom.
Array#sort sorts without callback by string and does not respect stringed numerical values.
var array = ['2','ZIRST','1','10','LAST','20', 'Sara'];
array.sort((a, b) => isNaN(a) - isNaN(b) || a - b || a > b || -(a < b));
console.log(array);
function sortArray(arr) {
let sortedArr = arr.sort();
sortedArr.forEach((v, i) => {
if (!isNaN(parseInt(v))) {
sortedArr[i] = parseInt(v);
} else {
sortedArr[i] = v;
}
});
return sortedArr.sort((a, b) => a - b).map(String);
}
// tests
console.log(sortArray(['2', '1','10','LAST','20']));
console.log(sortArray(['5','ZIRST','1','10','LAST','20', 'Sara']));
You need to check whether the given element in the array is number or not and then sort it accordingly for numbers and strings. You can create a reusable function sortNumber so that it can be used for multiple arrays and you do not need to duplicate the same logic again and again.
function sortNumber(a,b) {
return isNaN(a) - isNaN(b) || a - b;
}
var inputArray = ['2','1','10','LAST','20'];
inputArray.sort(sortNumber);
console.log(inputArray);
inputArray = ['21','31','110','LAST','220'];
inputArray.sort(sortNumber);
console.log(inputArray);
You can use localeCompare to sort an array on the numeric property.
const array = ["1", "5", "10", "20", "ZERO", "LAST", "Sara"];
array.sort((a, b) => a.localeCompare(b,undefined,{numeric: true}));
console.log(array);
You can use custom comparator like this:
var arr = ['2','1','10','LAST','20'];
arr.sort((a,b)=>{
return parseInt(a) > parseInt(b) || isNaN(a);
});
This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 4 years ago.
data = [{"map_name": "PHX7260.AE5020003.9"},
{"map_name": "PHX7260.AE5020003.10"},
{"map_name": "PHX7260.AE5020003.1"}]
I want to sort this data in descending order alphabetically and numerically both.
I tried the below but it doesn't work on array of objects.
var myArray = data;
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
console.log(myArray.sort(collator.compare));
How should I go about it, the data of objects is received and it should be returned as objects only and not as array to display.
You can use array#sort with string#localeCompare with numeric property set to true.
const data = [{"map_name": "PHX7260.AE5020003.9"}, {"map_name": "PHX7260.AE5020003.10"},{"map_name": "PHX7260.AE5020003.1"}];
data.sort((a,b) => b.map_name.localeCompare(a.map_name, undefined, {numeric: true}));
console.log(data);
Using javascript's native Array.sort() method, you can split your strings on . and do a multi-step sort like below:
var data = [{"map_name": "PHX7260.AE5020003.9"},
{"map_name": "PHX7260.AE5020003.10"},
{"map_name": "PHX7260.AE5020003.1"}]
function compare(a,b){
if(!!parseInt(a) && !!parseInt(b)){
a = parseInt(a)
b = parseInt(b)
}
if(a > b) return 1
else if(a < b) return -1
else return 0
}
function sortData(a,b){
let a_arr = a.map_name.split('.'),
b_arr = b.map_name.split('.')
while(a_arr.length){
let val = compare(a_arr.shift(), b_arr.shift())
if(val) return val
}
return 0
}
console.log(data.sort(sortData))
You can get the string and the number before/after the last dot respectively.
Compare the string first, if they are equal sort by number else use the function localeCompare.
This approach sorts using descending direction.
Look how ZHX7260.AE5020003.10 is placed at the first position.
var data = [{"map_name": "PHX7260.AE5020003.9"}, {"map_name": "ZHX7260.AE5020003.10"}, {"map_name": "PHX7260.AE5020003.10"}, {"map_name": "PHX7260.AE5020003.1"}];
data.sort((a, b) => {
var astr = a.map_name.substring(0, a.map_name.lastIndexOf('.'));
var bstr = b.map_name.substring(0, b.map_name.lastIndexOf('.'));
if (astr === bstr) {
var aidx = a.map_name.substring(a.map_name.lastIndexOf('.') + 1);
var bidx = b.map_name.substring(b.map_name.lastIndexOf('.') + 1);
return bidx - aidx;
} else return bstr.localeCompare(astr);
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
also since PHX7260.AE5020003 are same hence the output expected is above , if the string aredifferent it should sort the string first and then the number
I have to sort a string array based on the number.
Example
["1.READ","10.CREATE","3.sfg","2.dfd","12.dqwe"];
Desired Result
["1.READ","2.dfd","3.sfg","10.CREATE","12.dqwe"];
My Code
var arr = ["1.READ","10.CREATE","3.sfg","2.dfd","12.dqwe"];
var arr2 = arr.map( a => a.split('.').map( n => +n+100000 ).join('.') ).sort().map( a => a.split('.').map( n => +n-100000 ).join('.') );
console.log(arr);
console.log(arr2);
You can just split and convert the first element to Number
var arr = ["1.READ", "10.CREATE", "3.sfg", "2.dfd", "12.dqwe"];
var arr2 = arr.sort((a, b) => {
return Number(a.split(".")[0]) - Number(b.split(".")[0]);
});
console.log(arr2);
The code above will also sort the first variable. If you you only want arr2 to be sorted, you can:
var arr = ["1.READ", "10.CREATE", "3.sfg", "2.dfd", "12.dqwe"];
var arr2 = [...arr]; //Spread the array so that it will not affect the original
arr2.sort((a, b) => {
return Number(a.split(".")[0]) - Number(b.split(".")[0]);
});
console.log(arr);
console.log(arr2);
You could split and take only the first part. Then take the delta for sorting.
var array = ["1.READ", "10.CREATE", "3.sfg", "2.dfd", "12.dqwe"];
array.sort((a, b) => a.split(".")[0] - b.split(".")[0]);
console.log(array);
Here it is:
var arr = ["1.READ","10.CREATE","3.sfg","2.dfd","12.dqwe"];
arr.sort(function(a, b) {
return a.split('.')[0] - b.split('.')[0];
});
console.log(arr)
// ["1.READ", "2.dfd", "3.sfg", "10.CREATE", "12.dqwe"]
This answer base on built in array sort function, with customizable compare logic.
Check this out for more detail: Javascript Array Sort
Cheers,
I have the following array and sort result:
['53-15-9', '53-15-10', '53-15-8'].sort() // => ["53-15-10", "53-15-8", "53-15-9"]
but I need to get the following result:
["53-15-8", "53-15-9", "53-15-10"];
How could I get desired result?
To compare numbers instead of strings, first remove '-'. When you use arithmetic
operation, JavaScript first coverts it to numbers.
'53-15-9'.replace(/-/g,'') gives '53159'. You can use closures in sort() to pass compare function that can simply subtract a from b. The following function will sort the array ascending:
['53-15-9', '53-15-10', '53-15-8'].sort(function(a,b){
return a.replace(/-/g,'') - b.replace(/-/g,'')
})
Update
As mentioned in the comments, '54-1-1' is less than '53-15-9'. We can change '54-1-1' to '54-01-01'. This only works in double digits. We can do it like:
function customSort(myArray) {
myArray = myArray.map(function(a,b){
var ar = a.split('-');
return ar.map(function(arK, arV){return (arK<10)?'0'+arK : arK.toString();}).join('-');;
})
return myArray.sort(function(a,b){
return a.replace(/-/g,'') - b.replace(/-/g,'')
});
}
customSort(['54-1-2','53-15-9', '53-15-10', '53-15-8']);
// => ["53-15-08", "53-15-09", "53-15-10", "54-01-02"]
You can use a custom function for splitting and sorting the parts.
var array = ['53-15-9', '53-15-10', '53-15-8'];
array.sort(function (a, b) {
var aa = a.split('-'),
bb = b.split('-'),
i, r = 0, l = Math.max(aa.length, bb.length);
for (i = 0; !r && i < l; i++) {
r = (aa[i] || 0) - (bb[i] || 0);
}
return r;
});
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
['53-15-9', '53-15-10', '53-15-8'].sort(function(a, b) {
var aNum = parseInt(a.replace(/-/g, ''));
var bNum = parseInt(b.replace(/-/g, ''));
return aNum < bNum ? -1 : aNum > bNum ? 1 : 0;
});
Assuming you want to sort them in numerical order including all the sections, simply remove the -, parse them as an int and then sort the ints in a custom sort function.
var arr = ['53-15-9', '53-15-10', '53-15-8'];
arr.sort(function(a,b){ return a.replace(/-/g,'') - b.replace(/-/g,'') });
console.log(arr);
output
["53-15-8", "53-15-9", "53-15-10"]
Try comparing every number separated by - using Array.prototype.every()
var arr = ["53-15-8", "53-15-9", "53-15-10"];
arr.sort(function(a, b) {
var curr = a.split(/-/).map(Number);
var next = b.split(/-/).map(Number);
return curr.every(function(val, key) {return val <= next[key]}) ? a : b
});
console.log(JSON.stringify(arr))
You need to define your own custom sorting function. Here is an example:
['53-15-9', '53-15-10', '53-15-8','2', '53-14-4','53-15-99'].sort(function(a,b){ // a and b are elements of the array
// split by - and convert values to number
a = a.split('-').map(function(val){return Number(val)})
b = b.split('-').map(function(val){return Number(val)})
// if one has less elements than another, we consider it should go first
if(a.length != b.length) return a.length > b.length
//else, one goes after another if one of its elements is greater than the others at that index
return a.some(function(val, index){
return val > b[index]
}) == 0 ? -1 : 1
})
//output: ["2", "53-14-4", "53-15-8", "53-15-9", "53-15-10", "53-15-99"]