Arranging an array according to the length of another parameter array

Consider this array as an example -

[
  {
    "data": [
       1, 2, 3
    ]
  },
  {
    "data": [
      2, 3, 4, 5
    ]
  }
]

I want to arrange the main array based on the length of data. The object with the largest data array should come first, and the one with the smallest data array should come last.

Is there a way to achieve this?

JSFiddle: https://jsfiddle.net/tk7nybkq/

Answer №1

To obtain a sorted JSON array based on the 'data' key, you can utilize the sort() function with two parameters.

var arr = [
{
    "data": [
      8, 2, 3, 4, 5,6,7
    ]
  },
  {
    "data": [
       1, 2, 3
    ]
  },
  {
    "data": [
      2, 3, 4, 5
    ]
  },
  {
    "data": [
       4, 5
    ]
  }
];

arr.sort(function (first, second) {
    return first.data.length - second.data.length;
});

console.log(arr);

To enhance the output, I have included additional objects in the arr.

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

Mapping in React/Javascript: How to Efficiently Return Multiple Items

How can I efficiently return multiple outputs in a .map function, such as two separate console.log statements? For instance, the following code works: return ( <div className="App"> {mycataobjects.map((myobject) => console.lo ...

Error message encountered when utilizing the Three.js JSONLoader: "'onLoad is not a function'."

I'm currently working on setting up a simple scene with Three.js to display an imported mesh rotating. I pieced together a couple of examples from the Three.js documentation and ended up with the code below: var scene, camera, renderer; var geometry, ...

Loading routes directly in Angular 2

I've encountered an issue with my Angular application where navigating to certain routes results in an error. The two routes in question are: http://localhost:8080/ /* Landing page */ http://localhost:8080/details/:id /* Result page */ For instance, ...

Change the background color of the top element box when scrolling

The code I have implemented reflects my intentions. html: <div id="one" class="box"></div> <div id="two" class="box"></div> <div id="thr" class="box"></div> <div id="fou" class="box"></div> <div id="fiv" ...

jQuery's callback handling often reverses the statement I just made

My current project involves using AJAX with jQuery to send a get request. Once the request is successful, I insert the response into a specific div: $.get("content.php", function(result) { $('#content').html(result); The content I'm fetc ...

What could be causing slice to fail to slice an array?

I've been using the slice function for a while now without any issues, but I'm having trouble with .slice() not actually slicing the data. Code: (why is it not working as expected?) let data data = await Models.find().sort([['points', & ...

React TypeScript for Globalization and Language Support

As a newcomer to React, I am aiming to localize every component in my project. The file extension of the components is tsx. My goal is for the text to switch between English and French. I attempted using react-intl and react-i18n. However, I encountered ...

Ways to deactivate all click events excluding specified div elements

To disable clicking on all elements except specific ones such as buttons, anchors, inputs, selects, elements with the class '.nav-class', and checkboxes, the following jQuery code was written. However, the code does not seem to be working as expe ...

"Node.js mystery: Why does a function call return undefined, only to be evaluated

Utilizing the async module, I am running a series of functions in parallel. However, I have encountered an issue where the return value of another function is undefined because the callback does not wait for it to be evaluated. function getGenresId(genres ...

What sets Vuex apart from the Event Bus mechanism?

In my quest to grasp the intricacies of component communication, a question has surfaced: What sets Vue's event bus strategy apart from Vuex in handling inter-component communication? Additionally, when is the optimal moment to employ each technique a ...

Creating unique validation rules using VeeValidate 3 and vue.js

I have a form where I need to establish specific rules. For instance, consider the following code snippet: <label class="form-label">Price range from</label> <validation-provider rules="required_if:price_to" name="Price range from" ...

Encountering a 404 error when attempting to make an Axios post request

Utilizing Axios for fetching data from my backend endpoint has been resulting in a 404 error. Oddly enough, when I manually enter the URI provided in the error message into the browser, it connects successfully and returns an empty object as expected. Her ...

What is the best way to transfer information from jQuery to HTML?

Currently, I have a separate script written in jQuery that retrieves data from an API. function sendRequest() { $.ajax({ url: "http://localhost:3002/api/people", type: "get", //using get method data: { ...

Difficulty encountered when displaying JavaScript variable content within HTML in a React component

I'm currently exploring a backend administrative dashboard framework known as admin bro. My current project involves creating a tooltip component, and here is the code I have developed so far. class Textbox extends React.PureComponent { render() { ...

Utilizing HTML5 history instead of hash URLs to preserve the user's browsing history

Our application is a single page that dynamically loads results based on query strings. The query string format we use is as follows: ?city=Delhi&pn=1 Within the SPA, there are different sections displayed on the same page. As users navigate through ...

I am encountering an issue while developing a JavaScript filtering system

Hey everyone, I need help with coding a filter in JavaScript and I'm running into an error (Uncaught TypeError: todos.forEach is not a function) that I can't figure out. Can someone assist me in resolving this issue? const todoFilter = docume ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Synchronize the hiding and displaying of elements with a corresponding element

If I had a pair of <div> elements set up like this: <div class="overlay"></div> <!-- More content here --> <div class="popup"></div> Whenever the div.popup element is displayed with display: block, I want the div.overl ...

What is the method for retrieving post ID with the Google Feed API?

I am currently utilizing two different JS codes to dynamically load posts from my Wordpress website: Code 1: JSON API <script src="http://howtodeployit.com/category/daily-devotion/?json=recentstories&callback=listPosts" type="text/javascript">& ...

Bootstrap4: combining card header and navigation into a single row

How can we use Bootstrap 4 to position navigation and text within a Card Header in order to have them display on a single row? <div class="card"> <div class="card-header"> Heading <ul class="nav nav-pills card-header-pills"> ...