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!

5
  • What is the logic for sorting according to name or favouriteCream? Alphabetically? Commented Oct 18, 2017 at 21:56
  • Yes, would be alphabetically. either ascending or descending. Commented Oct 18, 2017 at 21:57
  • 2
    please try searching before asking. There are many many similar questions easily found already. See several links above Commented Oct 18, 2017 at 21:58
  • I think this question is still worth answering with ES6 argument destructure syntax. The other posts don't describe that functionality. Commented Oct 20, 2017 at 8: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. Commented Oct 20, 2017 at 17:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.