Organizing Parsed JSON Data with JavaScript: Using the _.each function for Sorting

var Scriptures = JSON.parse( fs.readFileSync(scriptures.json, 'utf8') );
_.each(Scriptures, function (s, Scripture) {
  return Scripture;
});

This code extracts and displays the names of each book from a collection of scriptures (e.g., Genesis, Exodus, Leviticus). The issue at hand is that the books in the JSON file are not arranged properly. Numerous attempts have been made to sort them within the _.each loop without success. An approach like this:

correctlyOrderedIndex.indexOf(Scripture) - correctlyOrderedIndex.indexOf(s);

accurately retrieved the index of each item, yet sorting them inside the _.each loop appears to be impossible. Is there a way to pre-arrange the order before entering the _.each loop or perhaps an alternative method to sort them while looping through?

Answer №1

Sorting inside the each function is not recommended as it may be too late in the process. However, you can sort before using _.each:

var Library = JSON.parse( fs.readFileSync(library.json, 'utf8') );
Library.sort(); // sorts the array in place
_.each(Library, function (item, index) { 
  return index; 
});

Alternatively, you can pass the sorted values as a parameter to each:

var Library = JSON.parse( fs.readFileSync(library.json, 'utf8') );
_.each(Library.sort(), function (item, index) { 
  return index; 
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: The absence of a default constructor in this class prevents instantiation

I am encountering the following issue: Error: The specified class must have a default constructor (a public constructor with no arguments) (com.mrad4tech.development.sportss.TwitterAPI) [Instantiatable] package com.mrad4tech.development.sportss; pub ...

Exploring the benefits of WordPress integration with form caching and dynamic show/hide div

Within my Wordpress (3.8.1) website, I have created a form that includes a checkbox. When this checkbox is clicked, a hidden div appears on the screen, prompting users to provide additional information. The JavaScript code responsible for showing the hidd ...

Adjust the sliders according to the current time

I am looking to display different sliders based on the time of day. For instance, 'slider set 1' from 0-9am, 'slider set 2' from 9am-12pm, and so forth. I am new to java script and need assistance in solving this challenge. Below is the ...

Is it possible for Apache to send a JSON response for 404 and other errors?

While there is a wealth of resources available for customizing 404 and other error pages, they typically only address modifying the content of the response in HTML format. This can be problematic if the client is an application making REST calls that expec ...

What's preventing my .NET 6 Minimal API from correctly deserializing the POST request body?

Currently, I have created a basic API using .NET 6 to log HTTP POST requests. However, even with this simple functionality, I am unable to get it working properly. Here are some things I have attempted: Changed my logMessage to a record Added a default c ...

Disabling dates in the second datetimepicker depending on following days selected in the first one

I have implemented the bootstrap date picker and I am using two textboxes for searching by date range. I want the second textbox to display the days after the date selected in the first textbox. Any suggestions would be appreciated. Here is the HTML code: ...

Transferring data between Javascript and PHP with AJAX and JQuery

I'm currently working on a basic web page that involves sending data from an HTML page to a PHP script and receiving some data back. My approach involves using AJAX, but for some reason, the PHP script doesn't seem to execute at all. Here's ...

Guide on appending a file to a formData object in vue.js

Having trouble adding the file from the input to the formData object. Even after trying multiple solutions, the object appears to be empty when I log it. Can't seem to figure out what's wrong. File Input: <input class="btn btn-sm btn-rounded ...

FitText.js malfunctioning

I'm currently experimenting with using FitText.js to dynamically adjust the size of headlines to fit within the limits of the browser width. Interestingly, while this script successfully resizes the text in multiple sections of my website, it seems t ...

Send JSON data that has been refined utilizing jQuery

I am attempting to create a filtered JSON response using jQuery following a successful GET request of the original JSON response. The initial JSON response is an array of products from our Shopify store for the specific collection page the user is viewing. ...

Utilizing Jquery selectors for elements that change dynamically

While this question may be common, I have yet to find a satisfactory answer that meets my needs. On one of the pages on my website, labeled A, there is a script being loaded: jQuery.getScript('js/jquery.tablesorter.min.js', function (data, statu ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

Stop users from being able to input line breaks by pasting

I am currently facing a challenge with my code. Within the code, I have included a textarea where users can input the title of an article, and I want this title to be restricted to only one line. To achieve this, I created a script that prevents users from ...

Leveraging editor.action.insertSnippet from a different plugin

I am attempting to enhance the functionality of VS Code by adding buttons to the status bar that automatically insert code snippets. I am utilizing this Extension for this purpose. Additionally, I have configured keybindings in my keybindings.json file whi ...

Using arrays in Three.js for material instead of MeshFaceMaterial: a guide

I'm starting out with three.js as a beginner. I've run into some issues with MeshFaceMaterial. If anyone has any advice or solutions, I would greatly appreciate it. Thank you in advance! ...

Rest API question: Based on the output provided, how should the URL format be correctly written?

If I were in charge of developing a rest api that generated the following result from the given URL: /owner/123/animal {     {       Owner: 123,       Animal: Cat     },     {       Owner: 123,       Animal: Dog     },     {   ...

What are some strategies to avoid serializing or deserializing a member of a specific type that cannot be modified?

An issue arises when attempting to deserialize RecurrenceInfo within a large project: Newtonsoft.Json.JsonSerializationException: Cannot populate list type DevExpress.XtraScheduler.CustomFieldCollection at Newtonsoft.Json.... <<< omitted 20 Ne ...

Issue: missing proper invocation of `next` after an `await` in a `catch`

I had a simple route that was functioning well until I refactored it using catch. Suddenly, it stopped working and threw an UnhandledPromiseRejectionWarning: router.get('/', async (req, res, next) => { const allEmployees = await employees.fi ...

Encountering an unrecoverable SyntaxError while trying to deploy a website on Netlify

When using commands like npm start, npm run build, and pm2 start server.js, everything runs smoothly without any errors. However, I encounter an issue when trying to deploy my project on Netlify. The Chrome console displays the error: Uncaught SyntaxError: ...

End the HTML page once the Flash (SWF) animation comes to a close

I have successfully exported my flash file to an HTML page. How can I make the page close automatically once the flash animation is finished? While I can use actionscript to stop the animation, I need the entire page to shut down on its own. I attempted u ...