Skip to main content
added 562 characters in body
Source Link
Shidersz
  • 17.2k
  • 2
  • 28
  • 52

You can use the compareFunction function with String::localeCompare() on the target keys:

const targetArray = [
    { targetKey: 'March' },
    { targetKey: 'Jan' },
    { targetKey: 'Feb' },
    { targetKey: 'Dec' }
];

targetArray.sort((a, b) => a.targetKey.localeCompare(b.targetKey));

console.log(targetArray)

And if you don't want to mutate (modify) the original array, you can clone it with slice() and then sort the cloned one.

const targetArray = [
    { targetKey: 'March' },
    { targetKey: 'Jan' },
    { targetKey: 'Feb' },
    { targetKey: 'Dec' }
];

let res = targetArray.slice(0).sort((a, b) => a.targetKey.localeCompare(b.targetKey));

console.log(targetArray)
console.log(res);

You can use the compareFunction function with String::localeCompare() on the target keys:

const targetArray = [
    { targetKey: 'March' },
    { targetKey: 'Jan' },
    { targetKey: 'Feb' },
    { targetKey: 'Dec' }
];

targetArray.sort((a, b) => a.targetKey.localeCompare(b.targetKey));

console.log(targetArray)

You can use the compareFunction function with String::localeCompare() on the target keys:

const targetArray = [
    { targetKey: 'March' },
    { targetKey: 'Jan' },
    { targetKey: 'Feb' },
    { targetKey: 'Dec' }
];

targetArray.sort((a, b) => a.targetKey.localeCompare(b.targetKey));

console.log(targetArray)

And if you don't want to mutate (modify) the original array, you can clone it with slice() and then sort the cloned one.

const targetArray = [
    { targetKey: 'March' },
    { targetKey: 'Jan' },
    { targetKey: 'Feb' },
    { targetKey: 'Dec' }
];

let res = targetArray.slice(0).sort((a, b) => a.targetKey.localeCompare(b.targetKey));

console.log(targetArray)
console.log(res);

Source Link
Shidersz
  • 17.2k
  • 2
  • 28
  • 52

You can use the compareFunction function with String::localeCompare() on the target keys:

const targetArray = [
    { targetKey: 'March' },
    { targetKey: 'Jan' },
    { targetKey: 'Feb' },
    { targetKey: 'Dec' }
];

targetArray.sort((a, b) => a.targetKey.localeCompare(b.targetKey));

console.log(targetArray)