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

How can I update the value of a span element that was added to the HTML document through an AJAX request?

When a modal is triggered on click, data is added to it through an AJAX request to a PHP file. After the AJAX call, I want the values in span elements within the modal to change simultaneously with the input field of the modal. I attempted this JavaScript ...

Error: React Select input control is throwing a TypeError related to event.target

Having trouble changing the state on change using a React Select node module package. It works with regular text input, but I can't quite get it to work with this specific component. The error message "TypeError: event.target is undefined" keeps poppi ...

Error encountered in onclick handler due to unterminated string literal in PHP and jQuery

Trying to utilize PHP to send variables into the onclick of an element is resulting in an "Unterminated string literal" error due to long strings. Below is a snippet of my PHP code: $query = $conn->prepare("SELECT Name, Image, Description, Link, Price, ...

Is there any npm module available that can generate user-friendly unique identifiers?

Struggling to come across a user-friendly and easily readable unique ID generator for storing orders in my backend system. I have considered using the timestamp method, but it seems too lengthy based on my research. ...

Is there a way to dynamically update the text in an HTML element with a randomly generated value using JavaScript?

Currently, I am working on a coding project where I am attempting to create a flip box that reveals the name of a superhero from an array when clicked by a user. The code pen link provided showcases my progress so far: https://codepen.io/zakero/pen/YmGmwK. ...

Failure in uploading JSON data in Jersey

My entity class has the following structure. @XmlRootElement public class ImageSuffix { @XmlAttribute private boolean canRead; @XmlAttribute private boolean canWrite; @XmlValue; private String value; } I have implemented a JAX- ...

Avoid triggering the pointerenter event when touching and subsequently moving into an element

I am currently working on a React application where I want to enable a user to touch one element and then move to an adjacent element while keeping the touch continuous. The issue I am facing is that the pointerover and pointerenter events only trigger whe ...

Redis: Unable to establish a connection as net.connect is not recognized as a

I'm struggling to integrate Redis with nodejs Encountering issues during execution Despite using the same code, I am facing this error: Here's my code snippet: import { createClient } from 'redis' export const client = createClient({ ...

Having issues with my AngularJS application not updating as expected

After creating a custom service to store all search parameters, I can easily access them from any part of my code. This ensures that the search parameters are always accurate. Below is the definition of the custom service: App.factory('filterService& ...

Guide on navigating an array of objects using the provided keys as a starting point in Javascript/Typescript

Assuming I have an array of objects structured like this: const events: Array<{year: number, month: number, date: number}> = [ {year: 2020, month: 10, date: 13}, {year: 2021: month: 3, date: 12}, {year: 2021: month: 9, date: 6}, {year: 2021: mont ...

Choose various selections from a drop-down menu using AngularJs

I am currently working on a project where I need to be able to select multiple options from a dropdown menu. The code snippet for this functionality looks like the following: //Controller $scope.data = [{id: 1, Country: Zambia}, {id: 2, Coun ...

Navigating through information using Axios in React JS

Issue Currently, I am facing a challenge while trying to iterate through the data retrieved from an API call using Axios in a React.js application. The response is successfully received, but I am encountering difficulties when trying to display the inform ...

EJS: Is there a way to display multiple populated collections from mongoose in EJS file?

Having trouble rendering multiple populated collections from mongoDB in EJS. To provide more context, I'll share snippets of my code: models, routes, and views. Model Schema var mongoose = require("mongoose"); var playerSchema = mongoose.Schema({ ...

Rest parameter ...args is not supported by Heroku platform

When interacting with Heroku, an error message SyntaxError: Unexpected token ... appears. What modifications should be made to this function for compatibility with Heroku? authenticate(...args) { var authRequest = {}; authRequest[ ...

The declaration file for module 'react/jsx-runtime' could not be located

While using material-ui in a react project with a typescript template, everything is functioning well. However, I have encountered an issue where multiple lines of code are showing red lines as the code renders. The error message being displayed is: Coul ...

Dynamically filter JSON fields based on value in PostgreSQL

  When working with a JSON column in a table, I am able to select nested properties like this: SELECT '{"monday": 123}'::json->>'monday'; --> returns 123 However, attempting to select properties dynamically does not yield th ...

In JavaScript, what do we call the paradigm where a variable equals a variable equals a function? Let's take

Feeling a bit overloaded at the moment, so forgive me if this question seems too simple. I managed to accidentally write some code in Jest for testing a Vue application that actually works: const updateMethod = wrapper.vm.updateMethod = jest.fn() expect(u ...

Upgrading the entire document's content using jQuery

I am dealing with an ajax response that provides the complete HTML structure of a webpage, as shown below: <!DOCTYPE> <html> <head> <!-- head content --> </head> <body> <!-- body content --> </b ...

What causes the inversion of height and width settings in react-webcam?

Currently utilizing react-webcam with the following configuration. <Webcam audio={false} screenshotFormat="image/jpeg" videoConstraints={{ facingMode: "environment", width: camera ...

Which comment widget/platform does 9GAG utilize?

I am in the process of developing a new website and I am looking for a comment system to use. The comment system that 9GAG is currently using really catches my eye. Take a look at this random post as an example: Despite searching through their source code ...