What is the best way to arrange the elements in this JavaScript array?

Is there a way to arrange this array in order?

[
  {id : 1, start : 60, end : 120},
  {id : 2, start : 100, end : 240},
  {id : 3, start : 700, end : 720}
]

LATEST UPDATE: Given the current format of my array, is it possible to sort it by the start value?

[{
  1:{start : 60, end : 120},
  2:{start : 100, end : 240},
  3:{start : 700, end : 720}
}]

Answer №1

Here we have an array of objects that requires sorting based on a specific criterion.

To achieve this, the sort method can be utilized:

var data = [{id : 1, start : 60, end : 120}, {id : 2, start : 100, end : 240},{id : 3, start : 700, end : 720}];

function sortByStart(a, b){
  return a.start - b.start;
}

data.sort(sortByStart);

Answer №2

Sorting objects with the same starting value may be necessary:

    [
      {id : 5, start : 30, end : 90},
      {id : 6, start : 50, end : 180},
      {id : 7, start : 600, end : 620}
    ]

B.sort(function(x, y){
    return x.start-y.start || x.end-y.end || x.id-y.id;
});

Answer №3

Now you have a unique array created from a pseudo-array object. To optimize this, consider converting the object to a real array, sorting it, and then converting it back:

const originalArray = [{
    1:{start : 60, end : 120},
    2:{start : 700, end : 720},
    3:{start : 100, end : 240}
}];
const pseudoArray = originalArray[0];
let arrayToSort = [];
for (const key in pseudoArray) {
    arrayToSort.push(pseudoArray[key]);
}
arrayToSort.sort((left, right) => left.start - right.start || left.end - right.end);
let resultPseudoArray = {};
for (let i = 0; i < arrayToSort.length; i++) {
    resultPseudoArray[i + 1] = arrayToSort[i];
}
const resultArray = [resultPseudoArray];

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

Guide to deactivating scrolling on a specific element using jQuery

Can anyone provide a solution for disabling scroll on the window but still allowing scrolling within a text area? I attempted to use the following code, but it ended up disabling everything entirely: $('html, body').css({ overflow: 'hid ...

Is there a way for me to consolidate the properties of a complex nested object into the top level of an array of objects through either moving or summing them up?

I have a collection array that looks like this: const collection = [ { "name": "Top1", "data": [ { "name": "shahnshah", "data": [ { ...

Gather image origins from a website, even if img tags are inserted through javascript or other methods during the page's rendering

I am looking to extract the URLs of all the images from a web page using C# and asp.net. Currently, I am utilizing: WebClient client = new WebClient(); string mainSource = client.DownloadString(URL); Afterwards, I am scanning the mainSource string for i ...

How can I eliminate the CSS value that was inherited?

Looking for a way to eliminate the effect of an inherited CSS property with Jquery. .class1 #id1 div.class2 input.class-input{ border-color: #bbb3b9 #c7c1c6 #c7c1c6; } Can someone explain how to delete this "border-color"? Thanks. ...

Implementing translation functionality within an AngularJs controller

Utilizing angular translate for translating certain words in the controller, with translation stored in json files within the html. // LABELS var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "Septe ...

Getting started with `sessionStorage` in a React application

Currently, I am attempting to save an item in sessionStorage prior to rendering. The code snippet I have looks like this: componentWillMount() { sessionStorage.setItem("isUserLogged", false); } However, I encountered an error stating th ...

Output repeated JSON Array in console using Node.js

Looking to identify duplicates within a JSON array based on the URL. var temp = [ { "name":"Allen", "site":"www.google.com/allen" }, { "name":"Chris", "site":&q ...

Unsure about the approach to handle this PHP/JSON object in Javascript/jQuery

From my understanding, I have generated a JSON object using PHP's json_encode function and displayed it using echo. As a result, I can directly access this object in JavaScript as an object. Here is an example: .done(function(response) { var ...

Fetching Date and Time from the Internet using PHP

While I understand that similar questions have been asked numerous times before, I have yet to find a solution that fits my specific needs. My question is regarding how to retrieve the current date and time from the internet rather than relying on the loc ...

Organizing files on a website for collaborative projects involving multiple team members

I am currently constructing a website with the following specifications: Pages are being loaded inline via AJAX. CSS, HTML, JavaScript, and PHP are all separated to facilitate collaboration on projects. While working on creating a dynamic <select> ...

Firefox returns empty computed value in getComputedStyle function

When I use getComputedStyle on an element that has defined properties for left, right, and bottom, I noticed that Chrome returns 'auto' as the value for top, whereas Firefox returns the pixel value. However, interestingly, the top value does not ...

Disconnecting from a specific client using socket.io in Node.js JavaScript after emitting data

Greetings, I am currently developing a unique "Chat" system. Server: NodeJs with express - https Communication: [email protected] Client: var socket = io.connect(); socket.emit('HELLO', {user:'someuserid'}); socket.on('WELC ...

Creating a unique-looking visual representation of progress with arcs

Looking to create a circular progress bar (see image below), with loading starting from the left bottom side up to the right bottom side. The empty state should be light-blue (#E8F6FD) and the progress color strong blue (#1CADEB). https://i.sstatic.net/VZ ...

Implementing the @media rule using Javascript

I'm trying to use JavaScript to add an image dynamically, but I want to remove it when the viewport is 600px or wider. This is my approach so far: var img = document.createElement('img'); // (imagine here all the other fields being defined ...

Clicking on the textarea changes the cursor's position

I've been working on adding an emoji function, but I'm facing an issue. Whenever I select an emoji from the dropdown while having text in the textarea and the cursor placed at the beginning of the text, the emoji always gets added to the end like ...

Revamp the HTML table with JavaScript headers

I imported data from a CSV file into an HTML table and here is how it appears: <div id="myTable" style="-ms-overflow-x: auto;"> <table> <tbody> <tr class="rownum-0"> <td>Make</td> ...

Tips for fixing the error "TypeError: result.select is not a function" in a Node.JS, Express JS, and MongoDB application

I'm currently working on developing a store API. My goal is to filter the results based on the field from req.query and select. Everything seems to be functioning properly except for the select part. Error: TypeError: result.select is not a function ...

I am experiencing difficulties in initializing a class (controller) in Nextjs version 13

I am working on an application built with Next.js where I have a controller class responsible for handling all the access functions, such as retrieving data from the database. However, I keep encountering this error message: Error [ReferenceError]: Cannot ...

The ng-repeat directive successfully renders elements such as <p>, <ul><li>, and more, but encounters issues when used with a select element that has the same data source

A component of an application that generates a list of popular phone and tablet models based on the selection of a mobile operating system is displayed below: <div class="input-field col s3"> <label class="active">Environment ( ...

Tips for positioning and resizing images within a changing DIV dimension

My DIV element is adjusting its size based on the browser window. Inside this DIV, there is an image that should fill up the entire browser window without stretching out of proportion when the window dimensions change. In addition, I want the image to be ...