user4513271
user4513271

Reputation:

Javascript: Sorting Parsed JSON within _.each loop

var Bible = JSON.parse( fs.readFileSync(bible.json, 'utf8') ); _.each(Bible, function (b, Book) { return Book; });

This outputs each book name from the Bible (ex. Genesis, Exodus, Leviticus, etc.). The problem is that the books from the JSON file are not in order. I have tried to sort them in various ways, but nothing seems possible inside of the _.each loop. When I did this:

correctlyOrderedList.indexOf(Book) - correctlyOrderedList.indexOf(b);

It returned the index of each one correctly, but I still can't sort those within the ).each loop as far as I am aware. Is there a way to order it prior to the _.each loop or is there a way to sort it within?

Upvotes: 0

Views: 520

Answers (1)

stj
stj

Reputation: 9097

You cannot sort inside each because that would be too late. But you can sort before using _.each:

var Bible = JSON.parse( fs.readFileSync(bible.json, 'utf8') );
Bible.sort(); // sorts in place
_.each(Bible, function (b, Book) { 
  return Book; 
});

Or pass the sorted value as a parameter to each:

var Bible = JSON.parse( fs.readFileSync(bible.json, 'utf8') );
_.each(Bible.sort(), function (b, Book) { 
  return Book; 
});

Upvotes: 1

Related Questions