0

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?

1
  • Try _.each(_.sort(Bible), function(..) {...}) Commented Feb 8, 2015 at 15:09

1 Answer 1

1

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; 
});
Sign up to request clarification or add additional context in comments.

3 Comments

This worked. In my case, I had to deal with the Bible variable a little differently because it was an object. After passing it through a couple for loops, I was able to produce a sortable array from the original object. var index = []; var correctOrder = canon.OT + canon.NT; for (book in Bible) {index.push([book]);}; for (var b=0, book, bible=[]; book=index[b]; ++b) {bible.push(book[0]);}; bible.sort(function(a, b) {return correctOrder.indexOf(a) - correctOrder.indexOf(b);}); Sorted & ready to go: _.each(bible, function (Book) {return Book});
This is likely messier than it needs to be, but it was the best I could come up with so far. I'm trying to make it less spaghettified. Your answer was definitely what I needed though, I just had to figure out how to convert the object into an array (I think that's what I did?).
After consulting a few other stack overflow answers, I discovered that underscore has a way to put keys into an array! This would have been huge to have understood a long time ago, but I suppose that's part of learning. Here's my cleaned up version: _.keys(Bible).sort(function(a, b) {return correctOrder.indexOf(a) - correctOrder.indexOf(b);}); bible.forEach(function getBooks(Book) {return Book});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.