0

I have this array of objects:

var obj = [ 
{name: Andrew, age: 19, favouriteCream: Vanilla},
{name: Carl, age:20, favouriteCream:Chocolate},
{name: Bob, age: 22, favouriteCream:Strawberry}
];

I am curious how to build a function to print out the array sorted by either name, age or favouriteCream. Was thinking about prompting a message where the user can input a word such as name, age, or cream (cream = favourite cream) and then have a function printSorted(sortedBy) {} where sortedBy would be the user's input, but can't get my head around it. Would it be possible to use a for loop get the index of each element and then use something like obj[idx].name or obj[idx].favouriteCream to sort the list with it?

Edit: If sorted by name, would be alphabetically, if sorted by age, either ascending or descending.

PS: I am extremely new to programming! Thanks in advance!

Imr Bent
  • 23
  • 4
  • What is the logic for sorting according to `name` or `favouriteCream`? Alphabetically? – guest271314 Oct 18 '17 at 21:56
  • Yes, would be alphabetically. either ascending or descending. – Imr Bent Oct 18 '17 at 21:57
  • 2
    please try searching before asking. There are many many similar questions easily found already. See several links above – charlietfl Oct 18 '17 at 21:58
  • I think this question is still worth answering with ES6 argument destructure syntax. The other posts don't describe that functionality. – Andrew Oct 20 '17 at 08:26
  • Hey Andrew, that would be useful. Also, people don't really comment their answers here so I'm exactly where I started cause even if i read the theory behind something and i don't see a solid example commented I don't get the main idea on how and why was the function constructed. – Imr Bent Oct 20 '17 at 17:31

0 Answers0