DEV Community

Sorting Arrays of Strings in JavaScript

Banesa Guaderrama on December 13, 2018

Sorting Arrays of Strings In JavaScript arrays have a sort( ) method that sorts the array items into an alphabetical order. The following illu...
Collapse
 
krofdrakula profile image
Klemen Slavič • Edited

There's a big caveat to this method of string sorting: it doesn't take Unicode and non-English alphabets into account. Depending on your application, you might want to consider using the String::localeCompare() instead which has built-in support for things like language-specific sort ordering, ignoring cases or diacritics:

const strings = ['č','é','A','b','Đ'];

const defaultSort = Array.from(strings).sort();

const simpleSort = Array.from(strings).sort((a, b) => a - b);

const localeSort = Array.from(strings).sort((a, b) => {
  return a.localeCompare(b, 'en', { sensitivity: 'base' });
});

console.log(defaultSort);
console.log(simpleSort);
console.log(localeSort);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
charlesmwray profile image
Charles Wray

Love this reply. It's exactly what I was looking for. I do want to comment that there is a typo in case someone else tries to use this like I did and it didnt work. In the localeSort variable assignment it should be

return a.localeCompare(b, 'en', { sensitivity: 'base' });

Collapse
 
ricardorien profile image
Ricardo Aguilar

Thanks! both anwser are awesome!

Collapse
 
maprangsoft profile image
Maprangsoft

thank you.

Collapse
 
artemkorenuk profile image
Артем Коренюк

thanks!

Collapse
 
christophdellavalle profile image
christophdellavalle

I know it is an extension of the topic... How can I add an argument to the callback-function? I want to sort Objects according to their properties.

example of not working dummy code:
var sortprop='weight';
animals.sort(function (a, b, sortprop){....});

Collapse
 
ferdiesletering profile image
Ferdie Sletering

Use a compare closure function.

const data = [ {name: 'Bob', age: 22 }, { name: 'Jason', age:33 }];
const newData = data.sort( compare('name') )

function compare(prop) {
    return function (a,b) {
    console.log(prop) // outputs -> name
    return -1; // sort stuff
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
xgqfrms profile image
xgqfrms

why this code not work?

var arr = [{
    type: "fruit",
    name: "banana"
}, {
    type: "fruit",
    name: "strawberry"
}, {
    type: "fruit",
    name: "apple"
}];

const sortName = (obj) => obj.name;
arr.sort((a, b) => sortName(a) - sortName(b) > 0 ? 1 : -1);

arr;
/*
[
  {
    "type": "fruit",
    "name": "apple"
  },
  {
    "type": "fruit",
    "name": "strawberry"
  },
  {
    "type": "fruit",
    "name": "banana"
  }
]
*/ 

Enter fullscreen mode Exit fullscreen mode
Collapse
 
xgqfrms profile image
xgqfrms • Edited

let arr = [
  {
    "type": "fruit",
    "name": "banana"
  },
  {
    "type": "fruit",
    "name": "strawberry"
  },
  {
    "type": "fruit",
    "name": "apple"
  }
];

const sortObjectArrayByStringKey = (arr = [], key = '') => {
  // 1. sort string keys ✅
  const sortKeys = arr.map(obj => obj[key]).sort();
  console.log(`sortKeys =`, JSON.stringify(sortKeys));
  let result = [];
  for(let sortKey of sortKeys) {
    // 2. custom order objetcs with sortKey 🚀
    result.push(arr.find(obj => obj[key] === sortKey))
  }
  console.log(`result =`, JSON.stringify(result));
  return result;
}

sortObjectArrayByStringKey(arr, 'name');
// sortKeys = ["apple","banana","strawberry"] ✅
// result = [{"type":"fruit","name":"apple"},{"type":"fruit","name":"banana"},{"type":"fruit","name":"strawberry"}] ✅
Enter fullscreen mode Exit fullscreen mode

作者:xgqfrms
链接:cnblogs.com/xgqfrms/p/18195429
来源:cnblogs.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
©xgqfrms 2012-2024
cnblogs.com 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!

Collapse
 
maprangsoft profile image
Maprangsoft

thank you.