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
1 hour ago
@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
1 hour ago
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
1 hour ago
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 1 hour ago
asked 1 hour ago
Komal Bansal
1385
1385
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
1 hour ago
@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
1 hour ago
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
1 hour ago
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
1 hour ago
@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
1 hour ago
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
1 hour ago
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
1 hour ago
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
1 hour ago
@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
1 hour ago
@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
1 hour ago
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
1 hour ago
@briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
– Nick Parsons
1 hour ago
add a comment |
8 Answers
8
active
oldest
votes
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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums array (and then sort)
const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
24 mins ago
add a comment |
The shortest is probably:
arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));
It returns strings first and there's a missing parenthesis at the end
– Sergio Tx
48 mins ago
@sergio yup, fixed
– Jonas Wilms
27 mins ago
@JonasWilms beaten me to it :)
– Jony-Y
23 mins ago
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 |
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
1 hour ago
2
@komala>b
returnstrue
orfalse
whereas a number is expected
– Jonas Wilms
1 hour ago
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
1 hour ago
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
1 hour ago
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
8 Answers
8
active
oldest
votes
8 Answers
8
active
oldest
votes
active
oldest
votes
active
oldest
votes
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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums array (and then sort)
const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
24 mins ago
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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums array (and then sort)
const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
24 mins ago
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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums 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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums 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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums 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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums array (and then sort)
const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
edited 1 hour ago
answered 1 hour ago
Nick Parsons
4,6442721
4,6442721
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
24 mins ago
add a comment |
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
24 mins ago
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
24 mins ago
performance here is bad. Jonas's solution wraps it up with a single sort.
– Jony-Y
24 mins ago
add a comment |
The shortest is probably:
arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));
It returns strings first and there's a missing parenthesis at the end
– Sergio Tx
48 mins ago
@sergio yup, fixed
– Jonas Wilms
27 mins ago
@JonasWilms beaten me to it :)
– Jony-Y
23 mins ago
add a comment |
The shortest is probably:
arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));
It returns strings first and there's a missing parenthesis at the end
– Sergio Tx
48 mins ago
@sergio yup, fixed
– Jonas Wilms
27 mins ago
@JonasWilms beaten me to it :)
– Jony-Y
23 mins ago
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 43 mins ago
answered 1 hour ago
Jonas Wilms
54.8k42749
54.8k42749
It returns strings first and there's a missing parenthesis at the end
– Sergio Tx
48 mins ago
@sergio yup, fixed
– Jonas Wilms
27 mins ago
@JonasWilms beaten me to it :)
– Jony-Y
23 mins ago
add a comment |
It returns strings first and there's a missing parenthesis at the end
– Sergio Tx
48 mins ago
@sergio yup, fixed
– Jonas Wilms
27 mins ago
@JonasWilms beaten me to it :)
– Jony-Y
23 mins ago
It returns strings first and there's a missing parenthesis at the end
– Sergio Tx
48 mins ago
It returns strings first and there's a missing parenthesis at the end
– Sergio Tx
48 mins ago
@sergio yup, fixed
– Jonas Wilms
27 mins ago
@sergio yup, fixed
– Jonas Wilms
27 mins ago
@JonasWilms beaten me to it :)
– Jony-Y
23 mins ago
@JonasWilms beaten me to it :)
– Jony-Y
23 mins ago
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.
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 1 hour ago
Nurbol Alpysbayev
3,5871227
3,5871227
add a comment |
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
1 hour ago
2
@komala>b
returnstrue
orfalse
whereas a number is expected
– Jonas Wilms
1 hour ago
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
1 hour ago
2
@komala>b
returnstrue
orfalse
whereas a number is expected
– Jonas Wilms
1 hour ago
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 1 hour ago
ksav
4,15721328
4,15721328
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
1 hour ago
2
@komala>b
returnstrue
orfalse
whereas a number is expected
– Jonas Wilms
1 hour ago
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
1 hour ago
2
@komala>b
returnstrue
orfalse
whereas a number is expected
– Jonas Wilms
1 hour ago
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
1 hour ago
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
1 hour ago
2
2
@komal
a>b
returns true
or false
whereas a number is expected– Jonas Wilms
1 hour ago
@komal
a>b
returns true
or false
whereas a number is expected– Jonas Wilms
1 hour ago
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
1 hour ago
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
1 hour ago
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 1 hour ago
answered 1 hour ago
Jack Bashford
5,30631234
5,30631234
@NurbolAlpysbayev Fixed now.
– Jack Bashford
1 hour ago
add a comment |
@NurbolAlpysbayev Fixed now.
– Jack Bashford
1 hour ago
@NurbolAlpysbayev Fixed now.
– Jack Bashford
1 hour ago
@NurbolAlpysbayev Fixed now.
– Jack Bashford
1 hour ago
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
1 hour ago
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
1 hour ago
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 1 hour ago
answered 1 hour ago
Sergio Tx
1,6711020
1,6711020
Explanation added with a link to MDN.
– Sergio Tx
1 hour ago
add a comment |
Explanation added with a link to MDN.
– Sergio Tx
1 hour ago
Explanation added with a link to MDN.
– Sergio Tx
1 hour ago
Explanation added with a link to MDN.
– Sergio Tx
1 hour ago
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 1 hour ago
PALLAMOLLA SAI
874
874
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 1 hour ago
answered 1 hour ago
bitifet
2,298623
2,298623
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
1 hour ago
@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
1 hour ago
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
1 hour ago