Change the order of elements in an array using JavaScript

I have a set of objects retrieved from an API.

let objectList = [
  {title: 'Big Bang Theory'},
  {title: 'Breaking Bad'},
  {title: 'Stranger Things'},
  {title: 'Game of Thrones'},
  {title: 'Money Heist'}
];

In my data, I want Game of Thrones to always appear before Stranger Things, while keeping the other elements in their original order. Sometimes the API will provide them correctly arranged, but sometimes they will be reversed like in the example above.

Does anyone have suggestions on the most efficient approach for achieving this?

I am aware of using a loop and conditional statements, but I believe there might be a more optimal solution available.

for(let i = 0; i < objectList.length; i++){
  if(objectList[i].title === 'Game of Thrones' && objectList[i - 1].name === 'Stranger Things'){
    let tempObject = objectList[i];
    objectList[i] = objectList[i - 1];
    objectList[i - 1] = tempObject;
  }
}

Alternatively, should I consider creating a new array rather than modifying the existing one?

Answer №1

let bands = [
  {name: 'Blur'},
  {name: 'The Beatles'},
  {name: 'Oasis'},
  {name: 'Elvis'},
  {name: 'Arctic Monkeys'},
];

// Find and rearrange the position of Oasis and Arctic Monkeys
let oasisIndex = -1, monkeyIndex = -1;                       
for(let i = 0; i < bands.length && (oasisIndex === -1 || monkeyIndex === -1); i++) { 
  if(bands[i].name === "Arctic Monkeys") monkeyIndex = i;
  else if(bands[i].name === "Oasis") oasisIndex = i;      
}

if(oasisIndex !== -1 && monkeyIndex !== -1 && monkeyIndex !== oasisIndex - 1) { 
  let monkeyBand = bands.splice(monkeyIndex, 1)[0];             
  bands.splice(oasisIndex, 0, monkeyBand);                   
}

console.log(bands);

Answer №2

Presented here is a function that accepts an array along with two specific item names from within that array. It works to ensure that the first specified item comes directly before the second specified item!

var arrangeProperly = function(arr, firstItem, secondItem) {
    // Locate the indices of the specified items
    var firstInd = -1;
    var secondInd = -1;
    for (var i = 0; i < arr.length; i++) {
         if (arr[i].name === firstItem) firstInd = i;
         if (arr[i].name === secondItem) secondInd = i;

         // Stop searching once both indices are found
         if (firstInd > -1 && secondInd > -1) break;
    }

    // Ensure correct order between the indices
    var loInd = Math.min(secondInd, firstInd);
    var hiInd = Math.max(secondInd, firstInd);

    // Items before and after specified indices
    var itemsBefore = arr.slice(0, loInd);
    var itemsAfter = arr.slice(hiInd + 1);

    // Items between the specified indices
    var itemsBetween = arr.slice(loInd + 1, hiInd);

    /*
    The strategy here involves adding items in particular sequence.
    We can add 'itemsBefore' at the beginning, 'itemsAfter' at the end.
    Handling items between depends on which of the specified items comes first.
    */

    var result = itemsBefore;

    if (secondInd < firstInd) {
        result.push(arr[firstInd]);
        result.push(arr[secondInd]);
    }

    result = result.concat(itemsBetween);

    if (secondInd > firstInd) {
        result.push(arr[firstInd]);
        result.push(arr[secondInd]);
    }

    result = result.concat(itemsAfter);

    return result;
};

Now implement this code on your custom array:

let arr = [
    {name: 'Forest'},
    {name: 'The Redwoods'},
    {name: 'Maple Trees'},
    {name: 'Palm Trees'},
    {name: 'Birch'}
];
let reOrderedArr = arrangeProperly(arr, 'Maple Trees', 'Palm Trees');

Note that for efficiency reasons, it might be advisable to consider improving your API setup.

Answer №3

To efficiently address this issue, my recommendation is to implement a specific sorting rule on the server side. If you need a quick fix for the client-side scenario, you can try the following approach:

let arr = [
  {name: 'Blur'},
  {name: 'The Beatles'},
  {name: 'Oasis'},
  {name: 'Arctic Monkeys'},
  {name: 'Elvis'}
]

console.log(arr.map(o => o.name))

let iO = arr.findIndex(o => o.name === 'Oasis')
let iA = arr.findIndex(o => o.name === 'Arctic Monkeys')

if ((iA !== -1 && iO !== -1) && iA > iO) {
  let o = arr[iO]
  let a = arr[iA]
  arr[iO] = a
  arr[iA] = o
}

console.log(arr.map(o => o.name))

Answer №4

One way to approach this problem is by using an object to store the names and then checking if both names are present in the object.

It's important to note that while using the Array#sort method can be helpful, the stability of its results may vary depending on the sorting algorithm being used.

let arr = [{ name: 'Blur' }, { name: 'The Beatles' }, { name: 'Oasis' }, { name: 'Arctic Monkeys' }, { name: 'Elvis' }],
order = { 'Arctic Monkeys': 1, Oasis: 2 };

arr.sort((a, b) => (b.name in order) && (a.name in order) ? order[a.name] - order[b.name] : 0);

console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

HighCharts fails to display on Polymer webpage

I am working on a project that involves using Polymer alongside HighCharts. Here is the code I have implemented: HTML : <div class="container" layout vertical center> <paper-shadow z="1" class="span-shadow"> <post-card id ...

Store data in Firebase Storage and retrieve the link to include it in Realtime Database

Utilizing Firebase Realtime Database and Firebase Storage for this application involves uploading images from the pictures array to Firebase Storage. The goal is to obtain the Firebase Storage link for each image, add it to the object pushed into imagesU ...

Aligning dynamically-sized TextInput in React Native

I am facing a challenge in centering a text input with a width that matches the length of the input text. I have tried using alignSelf: 'center' and alignItems: 'center', but the text input is not visible without specifying a width. Fo ...

Struggling with routing in Node.js while working on REST API development via HTTP

I am facing an issue while trying to complete a MEAN project. The client side is already done, but I am having trouble with the server side when attempting to make a new insertion (which is carried out using HTTP Post). Below, I will demonstrate how I hav ...

Implementing an Onclick function in HTML

I have an HTML code and I am looking to add an onclick event for a button named GET DATA. When the button is clicked, I want to send data for userId and categoryId to a PHP file. Can someone help me implement this functionality in my existing code? Here ...

Retrieve information from an external JSON file and display it in a jstree

I am trying to pass JSON data to a jstree object from an external file. The code snippet I have does not seem to be working properly. <script> $.jstree.defaults.core.themes.responsive = true; $('#frmt').jstree({ plugins: [" ...

Troubleshooting TypeScript window augmentation not functioning in individual modules

I would like to extend the window object with a new property. This can be achieved by adding the following code: // global.d.ts import { IConfig } from './src/models'; export {}; declare global { interface Window { _env: IConfig; ...

How to implement mouse event handling on elements in a d3.js integrated Vue component?

After successfully working with plain JavaScript to create an interactive D3.js map, I am now attempting to convert it into a Vue.js component. I have defined all functions as methods, but I am facing a challenge where none of the mouse events are being tr ...

jQuery does not have the capability to automatically calculate Value Added Tax on form submissions

I have included this section in my form to calculate the value added tax (VAT): <div class="col-md-4"> <div class="form-check"> <input type="radio" id="vat_on" name="vat" value=&q ...

Using Javascript to assign a hidden form value when the drop down selection changes - having trouble populating options from an array in Javascript

When using my JavaScript code to create 2 arrays for Product Category and Product selection, I encountered an issue. The user must first choose the type of Campaign they want to run before selecting the Product Category or Product. The 'Campaign' ...

Error 404 in NodeJS: Page Not Found

I recently started working with NodeJS to develop an ecommerce application. I have a ready-made design and all the front-end components built using AngularJS code. Everything seems to work fine - when clicking on any menu, the page content changes along wi ...

Guide: How to include a date value within a JSON format? [See code snippet below]

Currently, I am developing a react application that includes a form with sections for basic details and employment information. The form is almost completed, and I have successfully structured the data in JSON format for different sections. To see a work ...

Monitor checkbox status to trigger confirmation dialog

My goal is to prevent the checkbox from changing if 'NO' is clicked in a dialog. The dialog pops up, but I can't figure out how to wait for it to close before allowing the checkbox change. I've attempted using Promises and doing everyt ...

Custom number of arrays specified by the user

Currently working on coding: Main Class public class Ticket { // Method : Display the details of a ticket and list of Lucky Dip numbers on screen. public void displayTicket() { numbersClass.populateArray(); System.out ...

Deactivate numerous buttons with the help of jQuery

Within my MVC view, I have a Razor foreach loop that generates table rows with buttons: @foreach (var item in Model) { <tr> <td>@item.Id</td> <td> <button id="btn" class="button btn-primary" type= ...

Disseminate several outcomes using a Discord bot

My first experience using stackoverflow was to seek help regarding a bot created to post results whenever a new episode of a show in the search list is added on nyaa.si. The issue I'm facing is that the bot posts the same episode multiple times within ...

Unpacking jQuery's fancybox collection

Can anyone guide me to where I can locate the unpacked version of Jquery.fancybox-x.x.x.pack? I attempted to fix the code formatting manually in order to comprehend it better, but I'm still finding it challenging... ...

What methods can a server use to identify if JQuery Ajax's "withCredentials: true" option was utilized for CORS requests?

Currently, I am working on integrating CORS (Cross-origin resource sharing) into a framework. I understand that when an XMLHttpRequest request is made using Jquery's ajax(...) with the withCredentials property set to true, the server must specificall ...

Retrieve a specific value from an array of objects by searching for a particular object's value

Here is an example of an array of objects I am working with: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', ' ...

Retrieve data from two databases and display the information from two separate arrays on a single ejs page after making two separate database calls

Currently, I am faced with a challenge where I need to render a page by passing two arrays that are populated by two separate database calls. It seems that when I only pass one array to the ejs page, everything works as expected. For a single array, my a ...