Sort an array which contains number and strings
I am trying to sort an array which contains strings, numbers, and numbers as strings (ex. '1','2'). I want to sort this array so that the sorted array contains numbers first and then strings that contain a number and then finally strings.
var arr = [9,5,'2','ab','3',-1 ] // to be sorted
arr.sort()
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
//arr = [-1, "2", 5, 9, "ab"] // actual result
I have also tried
var number =;
var char =;
arr.forEach(a=>{
if(typeof a == 'number') number.push(a);
else char.push(a);
})
arr = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [-1, 5, 9, "2", "ab", "3"]// actual result
javascript arrays string numbers
add a comment |
I am trying to sort an array which contains strings, numbers, and numbers as strings (ex. '1','2'). I want to sort this array so that the sorted array contains numbers first and then strings that contain a number and then finally strings.
var arr = [9,5,'2','ab','3',-1 ] // to be sorted
arr.sort()
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
//arr = [-1, "2", 5, 9, "ab"] // actual result
I have also tried
var number =;
var char =;
arr.forEach(a=>{
if(typeof a == 'number') number.push(a);
else char.push(a);
})
arr = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [-1, 5, 9, "2", "ab", "3"]// actual result
javascript arrays string numbers
Is there any reason for "2" and "3" to be after9
? For that kind of sort, you can either sort twice or make a single unique complex sort.
– briosheje
Dec 28 '18 at 12:20
@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
Dec 28 '18 at 12:21
2
@briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
– Nick Parsons
Dec 28 '18 at 12:21
How should the "numbers as strings" be sorted? As nbers or as strings?
– Jonas Wilms
Dec 29 '18 at 13:27
add a comment |
I am trying to sort an array which contains strings, numbers, and numbers as strings (ex. '1','2'). I want to sort this array so that the sorted array contains numbers first and then strings that contain a number and then finally strings.
var arr = [9,5,'2','ab','3',-1 ] // to be sorted
arr.sort()
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
//arr = [-1, "2", 5, 9, "ab"] // actual result
I have also tried
var number =;
var char =;
arr.forEach(a=>{
if(typeof a == 'number') number.push(a);
else char.push(a);
})
arr = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [-1, 5, 9, "2", "ab", "3"]// actual result
javascript arrays string numbers
I am trying to sort an array which contains strings, numbers, and numbers as strings (ex. '1','2'). I want to sort this array so that the sorted array contains numbers first and then strings that contain a number and then finally strings.
var arr = [9,5,'2','ab','3',-1 ] // to be sorted
arr.sort()
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
//arr = [-1, "2", 5, 9, "ab"] // actual result
I have also tried
var number =;
var char =;
arr.forEach(a=>{
if(typeof a == 'number') number.push(a);
else char.push(a);
})
arr = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [-1, 5, 9, "2", "ab", "3"]// actual result
javascript arrays string numbers
javascript arrays string numbers
edited Dec 28 '18 at 12:36
asked Dec 28 '18 at 12:11
Komal Bansal
3219
3219
Is there any reason for "2" and "3" to be after9
? For that kind of sort, you can either sort twice or make a single unique complex sort.
– briosheje
Dec 28 '18 at 12:20
@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
Dec 28 '18 at 12:21
2
@briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
– Nick Parsons
Dec 28 '18 at 12:21
How should the "numbers as strings" be sorted? As nbers or as strings?
– Jonas Wilms
Dec 29 '18 at 13:27
add a comment |
Is there any reason for "2" and "3" to be after9
? For that kind of sort, you can either sort twice or make a single unique complex sort.
– briosheje
Dec 28 '18 at 12:20
@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
Dec 28 '18 at 12:21
2
@briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
– Nick Parsons
Dec 28 '18 at 12:21
How should the "numbers as strings" be sorted? As nbers or as strings?
– Jonas Wilms
Dec 29 '18 at 13:27
Is there any reason for "2" and "3" to be after
9
? For that kind of sort, you can either sort twice or make a single unique complex sort.– briosheje
Dec 28 '18 at 12:20
Is there any reason for "2" and "3" to be after
9
? For that kind of sort, you can either sort twice or make a single unique complex sort.– briosheje
Dec 28 '18 at 12:20
@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
Dec 28 '18 at 12:21
@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
Dec 28 '18 at 12:21
2
2
@briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
– Nick Parsons
Dec 28 '18 at 12:21
@briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
– Nick Parsons
Dec 28 '18 at 12:21
How should the "numbers as strings" be sorted? As nbers or as strings?
– Jonas Wilms
Dec 29 '18 at 13:27
How should the "numbers as strings" be sorted? As nbers or as strings?
– Jonas Wilms
Dec 29 '18 at 13:27
add a comment |
9 Answers
9
active
oldest
votes
It seems you have done most of the work in your second attempt.
All I have done here is used Array.concat
to join the sorted results of number
and char
together.
var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
var number = ;
var char = ;
arr.forEach(a => {
if (typeof a == 'number') number.push(a);
else char.push(a);
})
var sorted = number.sort().concat(char.sort());
console.log(sorted)
Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
– Komal Bansal
Dec 28 '18 at 12:35
3
@komala>b
returnstrue
orfalse
whereas a number is expected
– Jonas Wilms
Dec 28 '18 at 12:42
add a comment |
The shortest is probably:
arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));
It doesn't sort the string numbers though. Should it?
– NikxDa
Dec 29 '18 at 4:06
@nikxda it actually should
– Jonas Wilms
Dec 29 '18 at 10:19
Having this array:["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"]
sorts the"17"
before the"5"
.
– NikxDa
Dec 29 '18 at 13:24
@NikxDa well it sorts them lexicographically, not sure if that is wanted
– Jonas Wilms
Dec 29 '18 at 13:31
add a comment |
You can sort the integers first and then the non-integers by using .filter()
to separate both data-types.
See working example below (read code comments for explanation):
const arr = [9,5,'2','ab','3',-1];
const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)
const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
2
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
Dec 28 '18 at 13:41
5
On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
– YSC
Dec 28 '18 at 14:34
2
@Jony-Y disagree. Ifnums.includes(x)
would be replaced withtypeof x === "string"
it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]
– Jonas Wilms
Dec 28 '18 at 15:44
@JonasWilms To have the same effect, it should be!== "number"
.
– wizzwizz4
Dec 28 '18 at 15:46
not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
– Jony-Y
Dec 28 '18 at 15:49
|
show 2 more comments
Here you are!
const arr = [9,5,'2','ab','3',-1 ]
const numbers = arr.filter(i => typeof i === 'number');
const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
const strings = arr.filter(i => typeof i === 'string' && isNaN(i));
numbers.sort();
numerics.sort();
strings.sort()
const result = .concat(numbers, numerics, strings)
console.log(result)
My strategy was to first find all the three chunks (numbers, numerics and strings), then just concatting them.
add a comment |
Try using this:
var arr = [9,5,'2','ab','3',-1 ];
var number = ;
var strInt = ;
var char = ;
arr.forEach(a => {
if (typeof a === "number") {
number.push(a);
} else if (typeof a === "string" && /d/.test(a)) {
strInt.push(a);
} else {
char.push(a);
}
});
arr = number.concat(strInt.concat(char));
console.log(arr);
What this does is makes three arrays, one for numbers, one for strings containing numbers, and one for strings. It sorts each element into the appropriate array, then finally concatenates them all together in the correct order.
@NurbolAlpysbayev Fixed now.
– Jack Bashford
Dec 28 '18 at 12:30
add a comment |
Try this
const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
const sortedArr = arr.sort((a, b) => {
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
} else if (typeof a === 'number') {
return -1;
} else if (typeof b === 'number') {
return 1;
} else {
return a > b ? 1 : -1;
}
});
console.log(sortedArr);
This uses the Array.prototype.sort optional function to sort elements in one array. It must return a number. If the number > 0, b goes first. If the number < 0, a goes first. If it's 0, their position remains unchanged.
Explanation added with a link to MDN.
– Sergio Tx
Dec 28 '18 at 12:34
add a comment |
I wanted to take this a little bit further and avoid looping array multiple times for decreased complexity and therefore increased performance.
You could do a custom sort function where you calculate string values based on each character charCode
value and sum them up and other hand handle numbers as they are.
In this code example I then made string values in power of 5, that we can assure string values are larger than numeric values. This could be tweaked based on use case and which kind of data are you handling.
Downside of this approach is that performance is impacted based on how long strings are you handling so be aware of that as well.
var arr = [90000, 5, '2', 'ab', 'aa', '3', -1] // to be sorted
arr.sort((a,b) => {
if(typeof a === 'string') {
let temp = 0
for (let s of a) temp += s.charCodeAt(0)
a = Math.pow(temp, 5)
}
if(typeof b === 'string') {
let temp = 0
for(let s of b) temp += s.charCodeAt(0)
b = Math.pow(temp, 5)
}
return a - b
})
console.log(arr) // [-1, 5, 90000, "2", "3", "aa", "ab"]
add a comment |
var arr=[9,5,'2','ab','3',-1];
var string_arr=;
var number_arr=;
var string_number_arr=;
for(var i=0;i<arr.length;i++)
{
if(typeof(arr[i])=='number')
{
number_arr.push(arr[i]);
}
else if((Number(arr[i]).toString())=="NaN")
{
string_number_arr.push(arr[i]);
}
else
{
string_arr.push(arr[i]);
}
}
string_arr.sort();
number_arr.sort();
string_number_arr.sort();
var arr=number_arr.concat(string_arr,string_number_arr);
console.log(arr);
add a comment |
You can use Array .sort() method anyway.
You just need to provide a function to control sorting criteria for every comparsion.
Example:
// First of all discretize all kinds of data you want to deal with
function typeClassify(v) {
return typeof v == "number"
? "N"
: isNaN(v) ? "s" : "n"
// (Treat all non numeric values as strings)
;
};
// Second: implement the sorting function
function sortCriteria(a, b) {
var mode = typeClassify(a) + typeClassify(b);
switch (mode) {
case "NN":
return a - b;
case "nn":
return Number(a) - Number(b);
case "ss":
return a == b
? 0
: a > b
? -1 : 1
;
case "Nn":
case "Ns":
case "ns":
return -1;
case "nN":
case "sN":
case "sn":
return 1;
default:
throw "This must never happen";
};
};
// And finally provide that function as a callback for .sort() method
var arr = [9,5,'2','ab','3',-1 ] // to be sorted
console.log(arr.sort(sortCriteria));
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [ -1, 5, 9, '2', '3', 'ab' ] // obtained result
Obviously the functionality of typeClassify()
function can be flattened into sortCriteria()
to save a function call on every comparsion. I preferred to put it apart for the sake of clarity.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53958419%2fsort-an-array-which-contains-number-and-strings%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
It seems you have done most of the work in your second attempt.
All I have done here is used Array.concat
to join the sorted results of number
and char
together.
var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
var number = ;
var char = ;
arr.forEach(a => {
if (typeof a == 'number') number.push(a);
else char.push(a);
})
var sorted = number.sort().concat(char.sort());
console.log(sorted)
Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
– Komal Bansal
Dec 28 '18 at 12:35
3
@komala>b
returnstrue
orfalse
whereas a number is expected
– Jonas Wilms
Dec 28 '18 at 12:42
add a comment |
It seems you have done most of the work in your second attempt.
All I have done here is used Array.concat
to join the sorted results of number
and char
together.
var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
var number = ;
var char = ;
arr.forEach(a => {
if (typeof a == 'number') number.push(a);
else char.push(a);
})
var sorted = number.sort().concat(char.sort());
console.log(sorted)
Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
– Komal Bansal
Dec 28 '18 at 12:35
3
@komala>b
returnstrue
orfalse
whereas a number is expected
– Jonas Wilms
Dec 28 '18 at 12:42
add a comment |
It seems you have done most of the work in your second attempt.
All I have done here is used Array.concat
to join the sorted results of number
and char
together.
var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
var number = ;
var char = ;
arr.forEach(a => {
if (typeof a == 'number') number.push(a);
else char.push(a);
})
var sorted = number.sort().concat(char.sort());
console.log(sorted)
It seems you have done most of the work in your second attempt.
All I have done here is used Array.concat
to join the sorted results of number
and char
together.
var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
var number = ;
var char = ;
arr.forEach(a => {
if (typeof a == 'number') number.push(a);
else char.push(a);
})
var sorted = number.sort().concat(char.sort());
console.log(sorted)
var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
var number = ;
var char = ;
arr.forEach(a => {
if (typeof a == 'number') number.push(a);
else char.push(a);
})
var sorted = number.sort().concat(char.sort());
console.log(sorted)
var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
var number = ;
var char = ;
arr.forEach(a => {
if (typeof a == 'number') number.push(a);
else char.push(a);
})
var sorted = number.sort().concat(char.sort());
console.log(sorted)
answered Dec 28 '18 at 12:25
ksav
4,26221329
4,26221329
Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
– Komal Bansal
Dec 28 '18 at 12:35
3
@komala>b
returnstrue
orfalse
whereas a number is expected
– Jonas Wilms
Dec 28 '18 at 12:42
add a comment |
Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
– Komal Bansal
Dec 28 '18 at 12:35
3
@komala>b
returnstrue
orfalse
whereas a number is expected
– Jonas Wilms
Dec 28 '18 at 12:42
Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
– Komal Bansal
Dec 28 '18 at 12:35
Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
– Komal Bansal
Dec 28 '18 at 12:35
3
3
@komal
a>b
returns true
or false
whereas a number is expected– Jonas Wilms
Dec 28 '18 at 12:42
@komal
a>b
returns true
or false
whereas a number is expected– Jonas Wilms
Dec 28 '18 at 12:42
add a comment |
The shortest is probably:
arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));
It doesn't sort the string numbers though. Should it?
– NikxDa
Dec 29 '18 at 4:06
@nikxda it actually should
– Jonas Wilms
Dec 29 '18 at 10:19
Having this array:["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"]
sorts the"17"
before the"5"
.
– NikxDa
Dec 29 '18 at 13:24
@NikxDa well it sorts them lexicographically, not sure if that is wanted
– Jonas Wilms
Dec 29 '18 at 13:31
add a comment |
The shortest is probably:
arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));
It doesn't sort the string numbers though. Should it?
– NikxDa
Dec 29 '18 at 4:06
@nikxda it actually should
– Jonas Wilms
Dec 29 '18 at 10:19
Having this array:["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"]
sorts the"17"
before the"5"
.
– NikxDa
Dec 29 '18 at 13:24
@NikxDa well it sorts them lexicographically, not sure if that is wanted
– Jonas Wilms
Dec 29 '18 at 13:31
add a comment |
The shortest is probably:
arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));
The shortest is probably:
arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));
edited Dec 28 '18 at 13:22
answered Dec 28 '18 at 12:41
Jonas Wilms
55.7k42750
55.7k42750
It doesn't sort the string numbers though. Should it?
– NikxDa
Dec 29 '18 at 4:06
@nikxda it actually should
– Jonas Wilms
Dec 29 '18 at 10:19
Having this array:["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"]
sorts the"17"
before the"5"
.
– NikxDa
Dec 29 '18 at 13:24
@NikxDa well it sorts them lexicographically, not sure if that is wanted
– Jonas Wilms
Dec 29 '18 at 13:31
add a comment |
It doesn't sort the string numbers though. Should it?
– NikxDa
Dec 29 '18 at 4:06
@nikxda it actually should
– Jonas Wilms
Dec 29 '18 at 10:19
Having this array:["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"]
sorts the"17"
before the"5"
.
– NikxDa
Dec 29 '18 at 13:24
@NikxDa well it sorts them lexicographically, not sure if that is wanted
– Jonas Wilms
Dec 29 '18 at 13:31
It doesn't sort the string numbers though. Should it?
– NikxDa
Dec 29 '18 at 4:06
It doesn't sort the string numbers though. Should it?
– NikxDa
Dec 29 '18 at 4:06
@nikxda it actually should
– Jonas Wilms
Dec 29 '18 at 10:19
@nikxda it actually should
– Jonas Wilms
Dec 29 '18 at 10:19
Having this array:
["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"]
sorts the "17"
before the "5"
.– NikxDa
Dec 29 '18 at 13:24
Having this array:
["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"]
sorts the "17"
before the "5"
.– NikxDa
Dec 29 '18 at 13:24
@NikxDa well it sorts them lexicographically, not sure if that is wanted
– Jonas Wilms
Dec 29 '18 at 13:31
@NikxDa well it sorts them lexicographically, not sure if that is wanted
– Jonas Wilms
Dec 29 '18 at 13:31
add a comment |
You can sort the integers first and then the non-integers by using .filter()
to separate both data-types.
See working example below (read code comments for explanation):
const arr = [9,5,'2','ab','3',-1];
const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)
const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
2
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
Dec 28 '18 at 13:41
5
On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
– YSC
Dec 28 '18 at 14:34
2
@Jony-Y disagree. Ifnums.includes(x)
would be replaced withtypeof x === "string"
it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]
– Jonas Wilms
Dec 28 '18 at 15:44
@JonasWilms To have the same effect, it should be!== "number"
.
– wizzwizz4
Dec 28 '18 at 15:46
not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
– Jony-Y
Dec 28 '18 at 15:49
|
show 2 more comments
You can sort the integers first and then the non-integers by using .filter()
to separate both data-types.
See working example below (read code comments for explanation):
const arr = [9,5,'2','ab','3',-1];
const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)
const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
2
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
Dec 28 '18 at 13:41
5
On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
– YSC
Dec 28 '18 at 14:34
2
@Jony-Y disagree. Ifnums.includes(x)
would be replaced withtypeof x === "string"
it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]
– Jonas Wilms
Dec 28 '18 at 15:44
@JonasWilms To have the same effect, it should be!== "number"
.
– wizzwizz4
Dec 28 '18 at 15:46
not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
– Jony-Y
Dec 28 '18 at 15:49
|
show 2 more comments
You can sort the integers first and then the non-integers by using .filter()
to separate both data-types.
See working example below (read code comments for explanation):
const arr = [9,5,'2','ab','3',-1];
const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)
const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
You can sort the integers first and then the non-integers by using .filter()
to separate both data-types.
See working example below (read code comments for explanation):
const arr = [9,5,'2','ab','3',-1];
const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)
const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
const arr = [9,5,'2','ab','3',-1];
const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)
const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
const arr = [9,5,'2','ab','3',-1];
const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)
const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
edited Dec 28 '18 at 16:00
answered Dec 28 '18 at 12:30
Nick Parsons
4,8372721
4,8372721
2
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
Dec 28 '18 at 13:41
5
On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
– YSC
Dec 28 '18 at 14:34
2
@Jony-Y disagree. Ifnums.includes(x)
would be replaced withtypeof x === "string"
it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]
– Jonas Wilms
Dec 28 '18 at 15:44
@JonasWilms To have the same effect, it should be!== "number"
.
– wizzwizz4
Dec 28 '18 at 15:46
not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
– Jony-Y
Dec 28 '18 at 15:49
|
show 2 more comments
2
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
Dec 28 '18 at 13:41
5
On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
– YSC
Dec 28 '18 at 14:34
2
@Jony-Y disagree. Ifnums.includes(x)
would be replaced withtypeof x === "string"
it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]
– Jonas Wilms
Dec 28 '18 at 15:44
@JonasWilms To have the same effect, it should be!== "number"
.
– wizzwizz4
Dec 28 '18 at 15:46
not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
– Jony-Y
Dec 28 '18 at 15:49
2
2
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
Dec 28 '18 at 13:41
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
Dec 28 '18 at 13:41
5
5
On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
– YSC
Dec 28 '18 at 14:34
On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
– YSC
Dec 28 '18 at 14:34
2
2
@Jony-Y disagree. If
nums.includes(x)
would be replaced with typeof x === "string"
it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]– Jonas Wilms
Dec 28 '18 at 15:44
@Jony-Y disagree. If
nums.includes(x)
would be replaced with typeof x === "string"
it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]– Jonas Wilms
Dec 28 '18 at 15:44
@JonasWilms To have the same effect, it should be
!== "number"
.– wizzwizz4
Dec 28 '18 at 15:46
@JonasWilms To have the same effect, it should be
!== "number"
.– wizzwizz4
Dec 28 '18 at 15:46
not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
– Jony-Y
Dec 28 '18 at 15:49
not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
– Jony-Y
Dec 28 '18 at 15:49
|
show 2 more comments
Here you are!
const arr = [9,5,'2','ab','3',-1 ]
const numbers = arr.filter(i => typeof i === 'number');
const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
const strings = arr.filter(i => typeof i === 'string' && isNaN(i));
numbers.sort();
numerics.sort();
strings.sort()
const result = .concat(numbers, numerics, strings)
console.log(result)
My strategy was to first find all the three chunks (numbers, numerics and strings), then just concatting them.
add a comment |
Here you are!
const arr = [9,5,'2','ab','3',-1 ]
const numbers = arr.filter(i => typeof i === 'number');
const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
const strings = arr.filter(i => typeof i === 'string' && isNaN(i));
numbers.sort();
numerics.sort();
strings.sort()
const result = .concat(numbers, numerics, strings)
console.log(result)
My strategy was to first find all the three chunks (numbers, numerics and strings), then just concatting them.
add a comment |
Here you are!
const arr = [9,5,'2','ab','3',-1 ]
const numbers = arr.filter(i => typeof i === 'number');
const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
const strings = arr.filter(i => typeof i === 'string' && isNaN(i));
numbers.sort();
numerics.sort();
strings.sort()
const result = .concat(numbers, numerics, strings)
console.log(result)
My strategy was to first find all the three chunks (numbers, numerics and strings), then just concatting them.
Here you are!
const arr = [9,5,'2','ab','3',-1 ]
const numbers = arr.filter(i => typeof i === 'number');
const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
const strings = arr.filter(i => typeof i === 'string' && isNaN(i));
numbers.sort();
numerics.sort();
strings.sort()
const result = .concat(numbers, numerics, strings)
console.log(result)
My strategy was to first find all the three chunks (numbers, numerics and strings), then just concatting them.
const arr = [9,5,'2','ab','3',-1 ]
const numbers = arr.filter(i => typeof i === 'number');
const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
const strings = arr.filter(i => typeof i === 'string' && isNaN(i));
numbers.sort();
numerics.sort();
strings.sort()
const result = .concat(numbers, numerics, strings)
console.log(result)
const arr = [9,5,'2','ab','3',-1 ]
const numbers = arr.filter(i => typeof i === 'number');
const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
const strings = arr.filter(i => typeof i === 'string' && isNaN(i));
numbers.sort();
numerics.sort();
strings.sort()
const result = .concat(numbers, numerics, strings)
console.log(result)
answered Dec 28 '18 at 12:23
Nurbol Alpysbayev
3,8581227
3,8581227
add a comment |
add a comment |
Try using this:
var arr = [9,5,'2','ab','3',-1 ];
var number = ;
var strInt = ;
var char = ;
arr.forEach(a => {
if (typeof a === "number") {
number.push(a);
} else if (typeof a === "string" && /d/.test(a)) {
strInt.push(a);
} else {
char.push(a);
}
});
arr = number.concat(strInt.concat(char));
console.log(arr);
What this does is makes three arrays, one for numbers, one for strings containing numbers, and one for strings. It sorts each element into the appropriate array, then finally concatenates them all together in the correct order.
@NurbolAlpysbayev Fixed now.
– Jack Bashford
Dec 28 '18 at 12:30
add a comment |
Try using this:
var arr = [9,5,'2','ab','3',-1 ];
var number = ;
var strInt = ;
var char = ;
arr.forEach(a => {
if (typeof a === "number") {
number.push(a);
} else if (typeof a === "string" && /d/.test(a)) {
strInt.push(a);
} else {
char.push(a);
}
});
arr = number.concat(strInt.concat(char));
console.log(arr);
What this does is makes three arrays, one for numbers, one for strings containing numbers, and one for strings. It sorts each element into the appropriate array, then finally concatenates them all together in the correct order.
@NurbolAlpysbayev Fixed now.
– Jack Bashford
Dec 28 '18 at 12:30
add a comment |
Try using this:
var arr = [9,5,'2','ab','3',-1 ];
var number = ;
var strInt = ;
var char = ;
arr.forEach(a => {
if (typeof a === "number") {
number.push(a);
} else if (typeof a === "string" && /d/.test(a)) {
strInt.push(a);
} else {
char.push(a);
}
});
arr = number.concat(strInt.concat(char));
console.log(arr);
What this does is makes three arrays, one for numbers, one for strings containing numbers, and one for strings. It sorts each element into the appropriate array, then finally concatenates them all together in the correct order.
Try using this:
var arr = [9,5,'2','ab','3',-1 ];
var number = ;
var strInt = ;
var char = ;
arr.forEach(a => {
if (typeof a === "number") {
number.push(a);
} else if (typeof a === "string" && /d/.test(a)) {
strInt.push(a);
} else {
char.push(a);
}
});
arr = number.concat(strInt.concat(char));
console.log(arr);
What this does is makes three arrays, one for numbers, one for strings containing numbers, and one for strings. It sorts each element into the appropriate array, then finally concatenates them all together in the correct order.
var arr = [9,5,'2','ab','3',-1 ];
var number = ;
var strInt = ;
var char = ;
arr.forEach(a => {
if (typeof a === "number") {
number.push(a);
} else if (typeof a === "string" && /d/.test(a)) {
strInt.push(a);
} else {
char.push(a);
}
});
arr = number.concat(strInt.concat(char));
console.log(arr);
var arr = [9,5,'2','ab','3',-1 ];
var number = ;
var strInt = ;
var char = ;
arr.forEach(a => {
if (typeof a === "number") {
number.push(a);
} else if (typeof a === "string" && /d/.test(a)) {
strInt.push(a);
} else {
char.push(a);
}
});
arr = number.concat(strInt.concat(char));
console.log(arr);
edited Dec 28 '18 at 12:30
answered Dec 28 '18 at 12:25
Jack Bashford
5,72631235
5,72631235
@NurbolAlpysbayev Fixed now.
– Jack Bashford
Dec 28 '18 at 12:30
add a comment |
@NurbolAlpysbayev Fixed now.
– Jack Bashford
Dec 28 '18 at 12:30
@NurbolAlpysbayev Fixed now.
– Jack Bashford
Dec 28 '18 at 12:30
@NurbolAlpysbayev Fixed now.
– Jack Bashford
Dec 28 '18 at 12:30
add a comment |
Try this
const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
const sortedArr = arr.sort((a, b) => {
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
} else if (typeof a === 'number') {
return -1;
} else if (typeof b === 'number') {
return 1;
} else {
return a > b ? 1 : -1;
}
});
console.log(sortedArr);
This uses the Array.prototype.sort optional function to sort elements in one array. It must return a number. If the number > 0, b goes first. If the number < 0, a goes first. If it's 0, their position remains unchanged.
Explanation added with a link to MDN.
– Sergio Tx
Dec 28 '18 at 12:34
add a comment |
Try this
const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
const sortedArr = arr.sort((a, b) => {
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
} else if (typeof a === 'number') {
return -1;
} else if (typeof b === 'number') {
return 1;
} else {
return a > b ? 1 : -1;
}
});
console.log(sortedArr);
This uses the Array.prototype.sort optional function to sort elements in one array. It must return a number. If the number > 0, b goes first. If the number < 0, a goes first. If it's 0, their position remains unchanged.
Explanation added with a link to MDN.
– Sergio Tx
Dec 28 '18 at 12:34
add a comment |
Try this
const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
const sortedArr = arr.sort((a, b) => {
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
} else if (typeof a === 'number') {
return -1;
} else if (typeof b === 'number') {
return 1;
} else {
return a > b ? 1 : -1;
}
});
console.log(sortedArr);
This uses the Array.prototype.sort optional function to sort elements in one array. It must return a number. If the number > 0, b goes first. If the number < 0, a goes first. If it's 0, their position remains unchanged.
Try this
const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
const sortedArr = arr.sort((a, b) => {
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
} else if (typeof a === 'number') {
return -1;
} else if (typeof b === 'number') {
return 1;
} else {
return a > b ? 1 : -1;
}
});
console.log(sortedArr);
This uses the Array.prototype.sort optional function to sort elements in one array. It must return a number. If the number > 0, b goes first. If the number < 0, a goes first. If it's 0, their position remains unchanged.
const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
const sortedArr = arr.sort((a, b) => {
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
} else if (typeof a === 'number') {
return -1;
} else if (typeof b === 'number') {
return 1;
} else {
return a > b ? 1 : -1;
}
});
console.log(sortedArr);
const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
const sortedArr = arr.sort((a, b) => {
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
} else if (typeof a === 'number') {
return -1;
} else if (typeof b === 'number') {
return 1;
} else {
return a > b ? 1 : -1;
}
});
console.log(sortedArr);
edited Dec 28 '18 at 12:43
answered Dec 28 '18 at 12:23
Sergio Tx
1,6731020
1,6731020
Explanation added with a link to MDN.
– Sergio Tx
Dec 28 '18 at 12:34
add a comment |
Explanation added with a link to MDN.
– Sergio Tx
Dec 28 '18 at 12:34
Explanation added with a link to MDN.
– Sergio Tx
Dec 28 '18 at 12:34
Explanation added with a link to MDN.
– Sergio Tx
Dec 28 '18 at 12:34
add a comment |
I wanted to take this a little bit further and avoid looping array multiple times for decreased complexity and therefore increased performance.
You could do a custom sort function where you calculate string values based on each character charCode
value and sum them up and other hand handle numbers as they are.
In this code example I then made string values in power of 5, that we can assure string values are larger than numeric values. This could be tweaked based on use case and which kind of data are you handling.
Downside of this approach is that performance is impacted based on how long strings are you handling so be aware of that as well.
var arr = [90000, 5, '2', 'ab', 'aa', '3', -1] // to be sorted
arr.sort((a,b) => {
if(typeof a === 'string') {
let temp = 0
for (let s of a) temp += s.charCodeAt(0)
a = Math.pow(temp, 5)
}
if(typeof b === 'string') {
let temp = 0
for(let s of b) temp += s.charCodeAt(0)
b = Math.pow(temp, 5)
}
return a - b
})
console.log(arr) // [-1, 5, 90000, "2", "3", "aa", "ab"]
add a comment |
I wanted to take this a little bit further and avoid looping array multiple times for decreased complexity and therefore increased performance.
You could do a custom sort function where you calculate string values based on each character charCode
value and sum them up and other hand handle numbers as they are.
In this code example I then made string values in power of 5, that we can assure string values are larger than numeric values. This could be tweaked based on use case and which kind of data are you handling.
Downside of this approach is that performance is impacted based on how long strings are you handling so be aware of that as well.
var arr = [90000, 5, '2', 'ab', 'aa', '3', -1] // to be sorted
arr.sort((a,b) => {
if(typeof a === 'string') {
let temp = 0
for (let s of a) temp += s.charCodeAt(0)
a = Math.pow(temp, 5)
}
if(typeof b === 'string') {
let temp = 0
for(let s of b) temp += s.charCodeAt(0)
b = Math.pow(temp, 5)
}
return a - b
})
console.log(arr) // [-1, 5, 90000, "2", "3", "aa", "ab"]
add a comment |
I wanted to take this a little bit further and avoid looping array multiple times for decreased complexity and therefore increased performance.
You could do a custom sort function where you calculate string values based on each character charCode
value and sum them up and other hand handle numbers as they are.
In this code example I then made string values in power of 5, that we can assure string values are larger than numeric values. This could be tweaked based on use case and which kind of data are you handling.
Downside of this approach is that performance is impacted based on how long strings are you handling so be aware of that as well.
var arr = [90000, 5, '2', 'ab', 'aa', '3', -1] // to be sorted
arr.sort((a,b) => {
if(typeof a === 'string') {
let temp = 0
for (let s of a) temp += s.charCodeAt(0)
a = Math.pow(temp, 5)
}
if(typeof b === 'string') {
let temp = 0
for(let s of b) temp += s.charCodeAt(0)
b = Math.pow(temp, 5)
}
return a - b
})
console.log(arr) // [-1, 5, 90000, "2", "3", "aa", "ab"]
I wanted to take this a little bit further and avoid looping array multiple times for decreased complexity and therefore increased performance.
You could do a custom sort function where you calculate string values based on each character charCode
value and sum them up and other hand handle numbers as they are.
In this code example I then made string values in power of 5, that we can assure string values are larger than numeric values. This could be tweaked based on use case and which kind of data are you handling.
Downside of this approach is that performance is impacted based on how long strings are you handling so be aware of that as well.
var arr = [90000, 5, '2', 'ab', 'aa', '3', -1] // to be sorted
arr.sort((a,b) => {
if(typeof a === 'string') {
let temp = 0
for (let s of a) temp += s.charCodeAt(0)
a = Math.pow(temp, 5)
}
if(typeof b === 'string') {
let temp = 0
for(let s of b) temp += s.charCodeAt(0)
b = Math.pow(temp, 5)
}
return a - b
})
console.log(arr) // [-1, 5, 90000, "2", "3", "aa", "ab"]
var arr = [90000, 5, '2', 'ab', 'aa', '3', -1] // to be sorted
arr.sort((a,b) => {
if(typeof a === 'string') {
let temp = 0
for (let s of a) temp += s.charCodeAt(0)
a = Math.pow(temp, 5)
}
if(typeof b === 'string') {
let temp = 0
for(let s of b) temp += s.charCodeAt(0)
b = Math.pow(temp, 5)
}
return a - b
})
console.log(arr) // [-1, 5, 90000, "2", "3", "aa", "ab"]
var arr = [90000, 5, '2', 'ab', 'aa', '3', -1] // to be sorted
arr.sort((a,b) => {
if(typeof a === 'string') {
let temp = 0
for (let s of a) temp += s.charCodeAt(0)
a = Math.pow(temp, 5)
}
if(typeof b === 'string') {
let temp = 0
for(let s of b) temp += s.charCodeAt(0)
b = Math.pow(temp, 5)
}
return a - b
})
console.log(arr) // [-1, 5, 90000, "2", "3", "aa", "ab"]
edited yesterday
answered 2 days ago
Jimi Pajala
1,449315
1,449315
add a comment |
add a comment |
var arr=[9,5,'2','ab','3',-1];
var string_arr=;
var number_arr=;
var string_number_arr=;
for(var i=0;i<arr.length;i++)
{
if(typeof(arr[i])=='number')
{
number_arr.push(arr[i]);
}
else if((Number(arr[i]).toString())=="NaN")
{
string_number_arr.push(arr[i]);
}
else
{
string_arr.push(arr[i]);
}
}
string_arr.sort();
number_arr.sort();
string_number_arr.sort();
var arr=number_arr.concat(string_arr,string_number_arr);
console.log(arr);
add a comment |
var arr=[9,5,'2','ab','3',-1];
var string_arr=;
var number_arr=;
var string_number_arr=;
for(var i=0;i<arr.length;i++)
{
if(typeof(arr[i])=='number')
{
number_arr.push(arr[i]);
}
else if((Number(arr[i]).toString())=="NaN")
{
string_number_arr.push(arr[i]);
}
else
{
string_arr.push(arr[i]);
}
}
string_arr.sort();
number_arr.sort();
string_number_arr.sort();
var arr=number_arr.concat(string_arr,string_number_arr);
console.log(arr);
add a comment |
var arr=[9,5,'2','ab','3',-1];
var string_arr=;
var number_arr=;
var string_number_arr=;
for(var i=0;i<arr.length;i++)
{
if(typeof(arr[i])=='number')
{
number_arr.push(arr[i]);
}
else if((Number(arr[i]).toString())=="NaN")
{
string_number_arr.push(arr[i]);
}
else
{
string_arr.push(arr[i]);
}
}
string_arr.sort();
number_arr.sort();
string_number_arr.sort();
var arr=number_arr.concat(string_arr,string_number_arr);
console.log(arr);
var arr=[9,5,'2','ab','3',-1];
var string_arr=;
var number_arr=;
var string_number_arr=;
for(var i=0;i<arr.length;i++)
{
if(typeof(arr[i])=='number')
{
number_arr.push(arr[i]);
}
else if((Number(arr[i]).toString())=="NaN")
{
string_number_arr.push(arr[i]);
}
else
{
string_arr.push(arr[i]);
}
}
string_arr.sort();
number_arr.sort();
string_number_arr.sort();
var arr=number_arr.concat(string_arr,string_number_arr);
console.log(arr);
answered Dec 28 '18 at 12:57
PALLAMOLLA SAI
1074
1074
add a comment |
add a comment |
You can use Array .sort() method anyway.
You just need to provide a function to control sorting criteria for every comparsion.
Example:
// First of all discretize all kinds of data you want to deal with
function typeClassify(v) {
return typeof v == "number"
? "N"
: isNaN(v) ? "s" : "n"
// (Treat all non numeric values as strings)
;
};
// Second: implement the sorting function
function sortCriteria(a, b) {
var mode = typeClassify(a) + typeClassify(b);
switch (mode) {
case "NN":
return a - b;
case "nn":
return Number(a) - Number(b);
case "ss":
return a == b
? 0
: a > b
? -1 : 1
;
case "Nn":
case "Ns":
case "ns":
return -1;
case "nN":
case "sN":
case "sn":
return 1;
default:
throw "This must never happen";
};
};
// And finally provide that function as a callback for .sort() method
var arr = [9,5,'2','ab','3',-1 ] // to be sorted
console.log(arr.sort(sortCriteria));
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [ -1, 5, 9, '2', '3', 'ab' ] // obtained result
Obviously the functionality of typeClassify()
function can be flattened into sortCriteria()
to save a function call on every comparsion. I preferred to put it apart for the sake of clarity.
add a comment |
You can use Array .sort() method anyway.
You just need to provide a function to control sorting criteria for every comparsion.
Example:
// First of all discretize all kinds of data you want to deal with
function typeClassify(v) {
return typeof v == "number"
? "N"
: isNaN(v) ? "s" : "n"
// (Treat all non numeric values as strings)
;
};
// Second: implement the sorting function
function sortCriteria(a, b) {
var mode = typeClassify(a) + typeClassify(b);
switch (mode) {
case "NN":
return a - b;
case "nn":
return Number(a) - Number(b);
case "ss":
return a == b
? 0
: a > b
? -1 : 1
;
case "Nn":
case "Ns":
case "ns":
return -1;
case "nN":
case "sN":
case "sn":
return 1;
default:
throw "This must never happen";
};
};
// And finally provide that function as a callback for .sort() method
var arr = [9,5,'2','ab','3',-1 ] // to be sorted
console.log(arr.sort(sortCriteria));
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [ -1, 5, 9, '2', '3', 'ab' ] // obtained result
Obviously the functionality of typeClassify()
function can be flattened into sortCriteria()
to save a function call on every comparsion. I preferred to put it apart for the sake of clarity.
add a comment |
You can use Array .sort() method anyway.
You just need to provide a function to control sorting criteria for every comparsion.
Example:
// First of all discretize all kinds of data you want to deal with
function typeClassify(v) {
return typeof v == "number"
? "N"
: isNaN(v) ? "s" : "n"
// (Treat all non numeric values as strings)
;
};
// Second: implement the sorting function
function sortCriteria(a, b) {
var mode = typeClassify(a) + typeClassify(b);
switch (mode) {
case "NN":
return a - b;
case "nn":
return Number(a) - Number(b);
case "ss":
return a == b
? 0
: a > b
? -1 : 1
;
case "Nn":
case "Ns":
case "ns":
return -1;
case "nN":
case "sN":
case "sn":
return 1;
default:
throw "This must never happen";
};
};
// And finally provide that function as a callback for .sort() method
var arr = [9,5,'2','ab','3',-1 ] // to be sorted
console.log(arr.sort(sortCriteria));
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [ -1, 5, 9, '2', '3', 'ab' ] // obtained result
Obviously the functionality of typeClassify()
function can be flattened into sortCriteria()
to save a function call on every comparsion. I preferred to put it apart for the sake of clarity.
You can use Array .sort() method anyway.
You just need to provide a function to control sorting criteria for every comparsion.
Example:
// First of all discretize all kinds of data you want to deal with
function typeClassify(v) {
return typeof v == "number"
? "N"
: isNaN(v) ? "s" : "n"
// (Treat all non numeric values as strings)
;
};
// Second: implement the sorting function
function sortCriteria(a, b) {
var mode = typeClassify(a) + typeClassify(b);
switch (mode) {
case "NN":
return a - b;
case "nn":
return Number(a) - Number(b);
case "ss":
return a == b
? 0
: a > b
? -1 : 1
;
case "Nn":
case "Ns":
case "ns":
return -1;
case "nN":
case "sN":
case "sn":
return 1;
default:
throw "This must never happen";
};
};
// And finally provide that function as a callback for .sort() method
var arr = [9,5,'2','ab','3',-1 ] // to be sorted
console.log(arr.sort(sortCriteria));
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [ -1, 5, 9, '2', '3', 'ab' ] // obtained result
Obviously the functionality of typeClassify()
function can be flattened into sortCriteria()
to save a function call on every comparsion. I preferred to put it apart for the sake of clarity.
edited Dec 28 '18 at 13:00
answered Dec 28 '18 at 12:53
bitifet
2,328623
2,328623
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53958419%2fsort-an-array-which-contains-number-and-strings%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Is there any reason for "2" and "3" to be after
9
? For that kind of sort, you can either sort twice or make a single unique complex sort.– briosheje
Dec 28 '18 at 12:20
@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
Dec 28 '18 at 12:21
2
@briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
– Nick Parsons
Dec 28 '18 at 12:21
How should the "numbers as strings" be sorted? As nbers or as strings?
– Jonas Wilms
Dec 29 '18 at 13:27