Tips for organizing a JSON object based on an integer column such as "3", "2", "5"

I am facing a challenge with sorting a JSON object that has a column containing numbers. The issue arises because the column is of string type. How can I sort string numbers in numerical order?

var myArray = [{
  name: 'David',
  total: "6"
}, {
  name: 'John',
  total: "2"
}, {
  name: 'Joe',
  total: "8"
}, {
  name: 'Ana',
  total: "14"
}];

var ascending;
var descending;

function test1() {
  ascending = _.sortBy(myArray, 'total');
  console.log(JSON.stringify(ascending));
}

function test2() {
  descending = ascending.reverse();
  console.log(JSON.stringify(descending));

}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="701c1f1411031830445e41475e44">[email protected]</a>/lodash.min.js"></script>
<button onclick="test1()">Ascending</button>
<button onclick="test2()">Descending</button>

Answer №1

Implement _.sortBy() by using a callback function, and ensure to convert the values in the total field to numbers:

var myArray = [{"name":"David","total":"6"},{"name":"John","total":"2"},{"name":"Joe","total":"8"},{"name":"Ana","total":"14"}];

var ascending;
var descending;

function sortAscending() {
  ascending = _.sortBy(myArray, val => Number(val.total));
  console.log(JSON.stringify(ascending));
}

function sortDescending() {
  descending = ascending.reverse();
  console.log(JSON.stringify(descending));

}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b47444f4a58436b1f051a1c051f">[email protected]</a>/lodash.min.js"></script>
<button onclick="sortAscending()">Ascending</button>
<button onclick="sortDescending()">Descending</button>

Answer №2

Follow these steps to achieve it

To make a comparison in the sort, you need to convert strings to numbers.

var myArray = [{
  name: 'Alice',
  total: "9"
}, {
  name: 'Bob',
  total: "3"
}, {
  name: 'Charlie',
  total: "7"
}, {
  name: 'Denise',
  total: "12"
}];

var ascending;
var descending;

function sortAscending() {
  ascending = myArray.sort((a,b)=>Number(a.total)-Number(b.total));
  console.log(JSON.stringify(ascending));
}

function sortDescending() {
  descending = ascending.reverse();
  console.log(JSON.stringify(descending));

}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d5d4dfcaebf8eacadfc2ded7cddd">[email protected]</a>/lodash.min.js"></script>
<button onclick="sortAscending()">Sort Ascending</button>
<button onclick="sortDescending()">Sort Descending</button>

Answer №3

Transform the values of total in an array into numbers using map, then utilize the sort function.

This specific function arranges the elements of the array in ascending order.

var myArray = [{
  name: 'David',
  total: "6"
}, {
  name: 'John',
  total: "2"
}, {
  name: 'Joe',
  total: "8"
}, {
  name: 'Ana',
  total: "14"
}];

let sortedOrder = myArray.map((item) => {
  return {
    name: item.name,
    total: parseInt(item.total, 10)
  }
}).sort((a, b) => {
  return a.total - b.total;
})
console.log(sortedOrder)

Answer №4

const myList = [{
  name: 'Sarah',
  total: "10"
}, {
  name: 'Michael',
  total: "5"
}, {
  name: 'Emily',
  total: "3"
}, {
  name: 'Chris',
  total: "9"
}];

let ascendingOrder;
let descendingOrder;

/**
 * Ascending
 * Calls the sort function of the Array object.
 * - Processes the "total" property of each object.
 * -- Converts string numbers into integers for comparison.
 */
function testAscending() {
  ascendingOrder = myList.sort(function(a, b) { return parseInt(a['total']) > parseInt(b['total']); });
  console.log(JSON.stringify(ascendingOrder));
}

/**
 * Descending
 * Calls the sort function of the Array object.
 * - Processes the "total" property of each object.
 * -- Converts string numbers into integers for comparison.
 */
function testDescending() {
  descendingOrder = myList.sort(function(a, b) { return parseInt(a['total']) < parseInt(b['total']); });
  console.log(JSON.stringify(descendingOrder));

}
<button onclick="testAscending()">Ascending</button>
<button onclick="testDescending()">Descending</button>

Answer №5

To implement sorting by the property "total" as shown below:

function sortTotalProperty(prop) {  
    return function(x, y) {  
        if (parseInt(x[prop]) > parseInt(y[prop])) {  
            return 1;  
        } else if (parseInt(x[prop]) < parseInt(y[prop])) {  
            return -1;  
        }  
        return 0;  
    } 
}
myArray.sort(sortTotalProperty("total")); 

Answer №6

To implement sorting, you can utilize the _.orderBy function

var myArray = [{"name":"David","total":"6"},{"name":"John","total":"2"},{"name":"Joe","total":"8"},{"name":"Ana","total":"14"}];

var ascending;
var descending;

function sortAscending() {
  ascending = _.orderBy(myArray, v => parseInt(v.total),['asc']);
  console.log(JSON.stringify(ascending));
}

function sortDescending() {
  descending = _.orderBy(myArray, v => parseInt(v.total),['desc']);
  console.log(JSON.stringify(descending));

}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd9192999c8e95bdc9d3cccad3c9">[email protected]</a>/lodash.min.js"></script>
<button onclick="sortAscending()">Sort Ascending</button>
<button onclick="sortDescending()">Sort Descending</button>

Answer №7

No need to worry about loadlash, simply utilizing the .sort() function will suffice. Have a glance at the code snippet below:

var myArray = [{
  name: 'David',
  total: "6"
}, {
  name: 'John',
  total: "2"
}, {
  name: 'Joe',
  total: "8"
}, {
  name: 'Ana',
  total: "14"
}];

var ascending;
var descending;

function test1() {
  ascending = myArray.sort(function(a,b){
          return Number(a.total) - Number(b.total);
  });
  console.log(ascending)
}

function test2() {
  descending = myArray.sort(function(a,b){
          return Number(b.total) -  Number(a.total);
  });
  console.log(descending);

}
<button onclick="test1()">Ascending</button>
<button onclick="test2()">Descending</button>

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

Updating deeply nested document in Mongoose

Is it possible to change the value of array1.array2.status, according to the schema provided below? const SomeSchema = new mongoose.Schema({ status: Boolean, array1: [{ array2[{ status: boolean }] }] }) ...

Troubleshooting an issue in Chrome with animating the "d" value using Snap.svg

To uncover the issue, try opening in both Chrome and Safari browsers. The logo animation should animate one section at a time like it does in Safari, but in Chrome, the animation seems to freeze. Check out the Snap.svg function responsible for running th ...

Avoiding redundant data in CRUD applications

In a CRUD application (back-end using express and front-end using react-redux), form values are submitted to a mongodb database with the following schema: import mongoose from 'mongoose'; var Schema = mongoose.Schema({ createdAt:{ type: D ...

What is the process for sending an InMemoryUploadedFile to my S3 storage?

My upload form is quite simple and includes an image as a FileField: def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): inst ...

Arrange an array of objects based on boolean values first, followed by numerical values in JavaScript

I am facing a challenge where I have an array of objects that need to be sorted based on two rules, following a specific order: Firstly, objects with the "departeYet" property set to true should come first. Secondly, the objects must then be sorted numeri ...

Learn the technique for showcasing numerous markers on Google Maps, each equipped with its own individualized info windows

https://i.sstatic.net/1tTUD.png // map center var center = new google.maps.LatLng(2.855262784366583, 105.4302978515625); function initialize() { var mapOptions = { center: center, zoom: 7, mapTypeId: google.maps.MapTypeId.ROADMAP }; // Create a < ...

iOS app launch does not trigger Phonegap handleOpenURL

Receiving an alert message when the app is open in the background. However, when I close the app from the background and then relaunch it, the alert message doesn't appear. The handleOpenURL function cannot be invoked in JavaScript when the app is lau ...

The pre tag does not have any effect when added after the onload event

I have been experimenting with a jQuery plugin for drawing arrows, detailed in this article. When using the plugin, this code is transformed: <pre class="arrows-and-boxes"> (Src) > (Target) </pre> into this format: Src --> Target The ...

Sketch a straight path starting from the coordinates x,y at a specified angle and length

Is there a way to draw a line in Javascript starting from a specific x/y position with a given length and angle, without having to define two separate points? I have the x/y origin, angle, and length available. The line should be placed on top of a regula ...

Ways to interact with popup windows using Selenium

I'm currently using Selenium to automate a web task, and I'm facing an issue with clicking on a popup that appears after searching for an address. The popup displays a message asking, "Did you mean _____ address?" and I want to be able to click o ...

Angular request accessing CoinMarketCap API

Currently, I am immersing myself in the world of the latest CoinMarketCap API and navigating through the waters of data. The Node.js example below demonstrates how to make a request. But how can I achieve the same in Angular? Any tips or suggestions would ...

Maintain the newly selected background color for the current day in fullcalendar when navigating to the next or previous month

Currently, I am working on a project in React using npm fullcalendar. One of the requirements is to change the color of the current day. After some trial and error, I was able to achieve this by adding the following code: $('.fc-today').attr(&ap ...

Exploring AngularJS and the Power of i18next

After researching i18n plugins for Angular, I decided to use the i18next library instead of reinventing the wheel. To implement this, I created a directive named i18n that simply calls the i18n library: define(['app', 'jquery', 'i ...

CanvasJS showcasing a variety of pie charts

I need to generate multiple pie charts for a website, but I'm struggling with the idea of dynamically rendering them based on the required quantity. I know that I will have to create a maximum of 28 pie charts at once. My initial approach involves man ...

Is it possible to assign a value to the "input" that is different from the Vue variable?

I am looking to dynamically change the display of an input based on the value retrieved from a database for the variable: paragraph.RCBulletinNumber I have experimented with using the computed method, however, it seems that this approach may not be suitab ...

Parsing JSON data in Node.js using Express

I am attempting to extract the username from a JSON request. router.post('/', function (req, res) { console.log(req.body.username); }); Upon checking the console: undefined POST /question 200 39.384 ms - 28 When I modified it to this: rout ...

Using Axios: Manually Adding the X-XSRF-TOKEN Header

Currently, I am in the process of building a server-side rendered application with Vue. The API backend is created using Laravel framework and for sending requests to the API, I am utilizing axios. My current challenge involves making a POST request on th ...

"Discovering issues with the functionality of Antd Table's search and reset capabilities

I'm currently working on integrating search and reset functions in an Antd table. However, I am encountering an issue with the reset (clearAll) function as it does not revert the table back to its initial state when activated. The search functionality ...

Cloud Firestore trigger fails to activate Cloud function

I am facing an issue with triggering a Cloud Function using the Cloud Firestore trigger. The function is supposed to perform a full export of my sub collection 'reviews' every time a new document is added to it. Despite deploying the function suc ...

Incorporate a React web application seamlessly into a React Native WebView component

In my monorepo, I have a web app and a mobile app (built with React and React Native respectively). My goal is to embed the web app into the mobile app using React Native WebView. After reading the documentation, I learned that the source for the WebView ...