0

please suggest elegant ways to sort an array by data types. For example, sorting the following array:

testArray = ["1", "5", 4 , 8, [1,2,3], {test:"test"}, [1,3,4], {test2:"test2"}, 6, "test"]

to appear like that:

["1", "5", "test", 4, 6, 8, [1,2,3], [1,3,4], {test:"test"}, {test2:"test2"}]

The actual order of the datatypes doesn't really matter.

Thanks!

1 Answer 1

2

If you don't have to worry about certain edge cases like undefined and null, you could use value.constructor.name.

This will sort values by type "Array", "Number", "Object", "String", in that order:

const input = ["1", "5", 4 , 8, [1,2,3], {test:"test"}, [1,3,4], {test2:"test2"}, 6, "test"];
const sorted = input.sort((a, b) => (a.constructor.name).localeCompare(b.constructor.name));

console.log(JSON.stringify(sorted));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.