NOTE: I recommend checking out Andy's response, as it was posted earlier and my answer builds upon his.
Although this question is dated, I believe it's valuable to mention the use of Array.prototype.sort()
.
Here's an example from MDN along with the provided link
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// [1, 2, 3, 4, 5]
Fortunately, this method isn't limited to just sorting numbers:
arr.sort([compareFunction])
compareFunction
Defines a function that determines the sort order. If not specified, the array is sorted based on each character's Unicode code point value, according to the string conversion of each element.
I observed that you're arranging them by first name:
let playlist = [
{artist:"Herbie Hancock", title:"Thrust"},
{artist:"Lalo Schifrin", title:"Shifting Gears"},
{artist:"Faze-O", title:"Riding High"}
];
// sort by name
playlist.sort((a, b) => {
if(a.artist < b.artist) { return -1; }
if(a.artist > b.artist) { return 1; }
// names are equal
return 0;
});
Just a side note, if you wish to organize them by last name, consider including keys for both first_name
& last_name
, or explore regex techniques (which I'm unable to assist with XD)
Hope this information proves useful :)