0

Hello everyone I need a function so that i can sort an array of objects alphabeticaly by a certain property value.

Let say i have this array:

var myObj = [{Name: 'John'},
             {Name: 2.10},
             {Name: 'Andrew'},
             {Name: 10},
             {Name: 2.101}
            ];

The result should be 2.10, 2.101, 10, 'Andrew', 'John'. I need this sorting beacause in my program the Name property can be either a name as 'John' or and IP (like 1.0.0.14) or even a MAC address(97948453855)...

I have managed some sorting but it doesnt seem to work perfectly for both strings and numbers.

Thank you!

Cata John
  • 1,371
  • 11
  • 19
  • 1
    What is the basis of your sorting? Algorithm? – mehulmpt Mar 02 '17 at 18:31
  • Show what you tried so we can see where you went wrong. – epascarello Mar 02 '17 at 18:33
  • Please provide your code. – Amr Aly Mar 02 '17 at 18:33
  • 1
    Possible duplicate of [Sort array of objects by string property value in JavaScript](http://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript) – Jared Smith Mar 02 '17 at 18:34
  • This is an exact duplicate of another SO question *down to the **title***. Did you do *any* work at all? The other question is *literally* the top google hit for your question's title. – Jared Smith Mar 02 '17 at 18:35
  • I do not think it is a dupe of sorting array by object, I have a feeling the real question is how do you sort by type XXXX – epascarello Mar 02 '17 at 18:35
  • @epascarello I consider that sufficiently similar to count as a duplicate as you're still applying arbitrary predicate logic to filter a collection based on object properties. You can always not VTC if you disagree with me. – Jared Smith Mar 02 '17 at 18:37
  • 1
    A correct duplicate is probably how to sort alpha numeric content. – epascarello Mar 02 '17 at 18:39
  • Possible duplicate of [Sort Array Elements (string with numbers), natural sort](http://stackoverflow.com/questions/15478954/sort-array-elements-string-with-numbers-natural-sort) – baao Mar 02 '17 at 18:41

1 Answers1

3

You could check for string and use the delta as first result part, or take the nummerical delta or at last the string comparison.

var array = [{ Name: 'John' }, { Name: 2.10 }, { Name: 'Andrew' }, { Name: 10 }, { Name: 2.101 }];
            
array.sort(function (a, b) {
    return (typeof a.Name === 'string') - (typeof b.Name === 'string') || a.Name - b.Name || a.Name.localeCompare(b.Name);
});

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392