Extract an array from a JSON array based on the lowest value of the keys

Consider the following array:

[{
    "activity" : "Hiking",
    "level" : "8.5"
},
{
    "activity" : "Swimming",
    "level" : "-3.2"
}]

I want to loop through the JSON data and identify the object with the lowest value for level. In this example, I should retrieve

{
    "activity" : "Swimming",
    "level" : "-3.2"
}

Answer №1

Organize in an ascending order depending on the points and retrieve the initial element

var b = [{
    "activity": "Running",
    "points": "18"
  },
  {
    "activity": "Swimming",
    "points": "9"
  }
];
console.log(b.sort((c, d) => c.points - d.points)[0])

Answer №2

The recommended method to use in this scenario is parseInt:

let data = [{
    "subject" : "Math",
    "result" : "95"
},
{
    "subject" : "History",
    "result" : "75"
},
{
    "subject" : "Science",
    "result" : "82"
}];

let highestResult = data.reduce((prev, current) => parseInt(current.result) > parseInt(prev.result) ? current : prev);

Answer №3

Follow this code snippet to extract an array from a JSON Array with the lowest key's value

let myArray =[{
    "sport" : "Cricket",
    "score" : "22.45"
},
{
    "sport" : "Tennis",
    "score" : "-12"
},
{ "sport" : "Tennis", "score" : "-12000" }]

let minOfArray =myArray.reduce(function(prev, curr) {
    return parseInt(prev.score) < parseInt(curr.score) ? prev : curr;
});

console.log(minOfArray);

Answer №4

To find the lowest score among your items, you can utilize the reduce method in JavaScript:

const data = [{
  "sport" : "Football",
  "score" : "14.75"
}, {
  "sport" : "Basketball",
  "score" : "9.8"
}];

const result = data.reduce((acc, x) => x.score < acc.score ? x : acc, data[0]);

console.log(result);

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

Sending JSON data stored in a JavaScript variable through a jQuery POST request

I am currently attempting to retrieve data from a remote location using a JQuery post method. It works perfectly fine when I directly input the data to be posted, but for some reason, it fails when I store the JSON in a JavaScript variable and pass it in. ...

Comparing a number to the sum of numbers in JavaScript using VUE

Newbie in the world of JavaScript and VUE. In my data, I have a variable called numberOfItems with a value of 10. I am trying to check if this value is equal to the total sum of 5 different variables. var numberOfItems = 10 var destinations = (this.campa ...

Conditionally show a button in an Angular application based on the truthiness of a boolean value

I'm currently developing a simple angular Single Page Application (SPA) for a Pizzeria. Within my application, I have an array that contains various types of Pizzas with string, number, and boolean data types. Using this array, I am dynamically gene ...

Display One Div at a Time in Sequence on Page Load Using jQuery

I have come across this question multiple times: How to Fade In images on page load using JavaScript one after the other? Fade in divs sequentially Using jQuery .fadeIn() on page load? Despite trying various recommended methods, I'm still unable t ...

Nested validation schema featuring conditional validation - yes, we've got it covered!

In my Formik object, I have set initial values as follows: {customerDetails: {id: "", name: "", mobileNumber: ""}, notes: {id: "", text: "", type: ""}} How can I create a conditional Yup validati ...

Preventing PCs from accessing a specific webpage: A step-by-step guide

I am currently using the code below to block phones: if { /Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i .test(navigator.userAgent)) { window.location = "www.zentriamc.com/teachers/error ...

Guide to retrieving data from a URL and storing it in a string variable with JavaScript

Attempting to retrieve the JSON data from a specific URL and store it in a variable. The code snippet below successfully loads the JSON into a div element: $("#siteloader").html('<object data="MYURL">'); However, the goal is to extract t ...

Is there a way to incorporate a component into Particle.js?

I attempted to encase the Particle around the component but it's not functioning correctly import React from "react"; import { render } from "react-dom"; import Particles from "./Particles"; import "./index.css" ...

Building a custom WebRTC Unity to JavaScript client for one-way video streaming within the local network

In this project, Unity is used to capture video and it communicates with JavaScript via WebRTC. Despite successful communication between the two clients, the JavaScript client is unable to display any video from the Unity client. The issue of no video out ...

Show a selection of assorted files stored in the database

router.get("/alw", function(req, res){ Product.find({"category": "alw"}, function(err, allProduct){ if (err){ console.log(err) } else { res.render("products/alw", {products ...

How to extract data from a span element using AngularJS

Combining input values to create a cohesive string: <input ng-model="first"> <input ng-model="second"> <span ng-model="result">{{first}} and {{second}}</span> Is there a way to retrieve the resulting string from JavaScript? I&apos ...

Tips for launching and troubleshooting an AngularJS application within Eclipse

Looking to dive into Nodeclipse and get up and running with debugging an AngularJS application like the angular-phonecat example from Eclipse. Specifically, I want to utilize a Debug on Server launcher to kick off a server with my app and launch a web b ...

Creating PDFs in Angular 8 with jsPdf

Currently, I am utilizing jsPdf to create a PDF document that captures the contents of my HTML screen. Upon completion, the downloaded PDF file appears in my download folder. Is it possible to alter the default download path for the PDF? Instead of the st ...

Guide on incorporating a bespoke cordova plugin into your Ionic 4 project

After successfully completing all the necessary steps to create a new Cordova plugin as outlined in the link below: Start android activity from cordova plugin I executed the command cordova plugin ls which returned the following result: com.example.sam ...

What is the best way to load an image file using JavaScript and store it in a separate directory?

Is there a way to transfer an image file from one directory to another by clicking a button using Javascript that will work on all browsers (IE, FF, Chrome)? I already have code for this: <input type="button" name="button" value="Move image to another ...

How can I reduce the burden of dependencies on users with a pre-built NPM package?

I recently took over maintenance of an NPM package. It has a unique setup where the main file is located in the 'dist/' directory and it's built using webpack (via 'npm run build'). While this works for us, installing this package ...

The use of the "declare" keyword is prohibited within the `script setup` section of Vue

I need to integrate the function getCookie into my Vue file. This function is already defined in the HTML file where the Vue file will be injected. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" ...

How can you trigger a link click event when clicking anywhere on the page using Jquery?

Here's the code I'm working with: <a href="http://google.com" target="_blank">Open in new tab </a> I am trying to make it so that when a user clicks anywhere on the website, the link above will be automatically clicked and a new tab ...

Preventing Scope Problems in AngularJS

Spending more than 4 hours trying to figure out why my ng-model directive was not correctly binding with ng-options within my controller was frustrating. The <select> element seemed to be initialized properly, receiving a value from the parent scope, ...

The problem with the Image Gallery carousel not functioning properly in a right-to-left direction arises when attempting to modify

I have been developing an image gallery that functions perfectly in the English version of the website. Now, I am tasked with replicating the same functionality for another version of the website that requires right-to-left (RTL) direction. However, when I ...