Is there a way to rearrange the order of objects in an AngularJS application based on their index

Within my angularjs application, I am working with a collection of objects.

$scope.itemsList = [
  {  
    "setupId": "T_2893",   
    "name" : "abc"

  },
  {   
    "setupId": "LBT826",   
    "name" : "xyz"

  },
  {   
    "setupId": "LBT1252",
   "name" : "pqr"

  },
  {   
    "setupId": "G1252",
   "name" : "dwr"

  }
] 

When invoking the $scope.changeOreder(1, 3) function, the objective is to rearrange the objects based on the previous and next index. The updated list should appear as follows:

  $scope.itemsList = [
      {  
        "setupId": "T_2893",   
        "name" : "abc"

      },      
      {   
        "setupId": "LBT1252",
       "name" : "pqr"

      },
      {   
        "setupId": "G1252",
       "name" : "dwr"

      },
       {   
        "setupId": "LBT826",   
        "name" : "xyz"

      }
    ] 

If calling $scope.changeOreder(2, 0), the new order will be as follows:

$scope.itemsList = [
          {   
            "setupId": "G1252",
           "name" : "dwr"

          },
          {  
            "setupId": "T_2893",   
            "name" : "abc"

          },      
          {   
            "setupId": "LBT1252",
           "name" : "pqr"

          },          
           {   
            "setupId": "LBT826",   
            "name" : "xyz"

          }
        ] 

While attempting to implement the $scope.changeOrder function, I have experimented with various approaches such as creating a backup of the object at the prevIndex, then removing the object at prevIndex in order to insert the backed-up object at newIndex. However, due to deleting the object, the newIndex becomes invalid within the current list!!! Despite trying different methods, the final list does not get ordered in the expected manner. Any assistance in resolving this issue would be greatly appreciated.

Answer №1

Shifting an element to a specific position:

var items = [
          {   
            "setupId": "G1252",
           "name" : "dwr"

          },
          {  
            "setupId": "T_2893",   
            "name" : "abc"

          },      
          {   
            "setupId": "LBT1252",
           "name" : "pqr"

          },          
           {   
            "setupId": "LBT826",   
            "name" : "xyz"

          }
        ];


function moveElement(indexA, indexB) {
  /*
  * When an element is moved from a higher index to a lower index, it requires
  * removing the existing element first and then adding it.
  * Moving an element from a lower index to a higher index involves adding
  * the element first and then deleting it.
  */
  var upToDown = indexA > indexB;


  var elementToMove = items[indexA];
  //Create a copy first
  var tempList = items.slice(0); 

  if (!upToDown) {
      //Add element to the specified index
    tempList.splice(indexB+1, 0, elementToMove); 

    //Remove the old element
    tempList.splice(indexA, 1); 
  } else { 
    //Remove the old element
    tempList.splice(indexA, 1); 
      //Add element to the specified index
    tempList.splice(indexB, 0, elementToMove);

  }
  return tempList;
} 

var outcome = moveElement(0, 3); 
console.log(outcome);  

Plunk: https://plnkr.co/edit/23DGzcXBEY7qrqFWsQNA?p=preview

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

When attempting to import Quill-blot-formatter with react-quill via next/dynamic, the registration process fails and continues to display a loading message

After creating a function component and configuring quill-blot-formatter with react-quill, I added the blotFormatter to the modules list. Then, I imported this module using next/dynamic on the desired page. The custom function looks like this: import Reac ...

Implementing Pagination Functionality Using Knockout.js

Sample JSON Data [{ "name": "A Goofy Movie (1995) 720p HDTVRip x264 Eng Subs [Dual Audio] [Hindi DD 2.0 - English DD 2.0] Exclusive By -=!Dr.STAR!=-", "progress": 0, "size": "1.06 GB", "downloaded": "87.98 KB", "hash": "8fe65e43464debe ...

Move images horizontally next to the height of an element

I am attempting to increase the top attribute in relation to the element it is currently adjacent to. The element should only scroll directly next to the other element and cease when it surpasses the height of that element. My Goal: I want the image to re ...

Converting JSON to C# with Class hierarchy: Step-by-step guide

I am struggling with deserializing a JSON object using a class. I have tried looking at various references, but none seem to work in this particular case. Can someone please provide guidance on how to create a class that can properly deserialize the given ...

Creating a customer profile using credit card details with Stripe

Assuming the customer has provided their credit card information, I can create a one-time charge object using the following code: let tok = await stripe.tokens.create({ card: { number: '4242424242424242', exp_month: 12, exp_year ...

Library for enhancing and inheriting HTML templates using JavaScript

I'm looking for a solution to easily inherit one HTML template(file) from another. Here's how I envision it: parent.html: <h1><!-- header --></h1> <div class="container"> <!-- container --> </div> child.ht ...

Arranging Data in AngularJS based on Selected Filter Criteria

I have a filter function that currently only returns the name values in my table. I would like to add options for both ascending and descending sorting to this filter. Progress So Far: I am able to retrieve values from all inputs, including the name and ...

Utilize the toString method on a JSON object with the help of JAXB

Currently, I am delving into the world of Java and MongoDB, specifically focusing on creating a RESTful service. Everything is functioning properly, but there is one aspect of my Cliente class that I would like to modify during deserialization - the privat ...

What steps are involved in establishing client-side AJAX polling?

I need some assistance with my app's functionality regarding Delayed::Jobs. Time to reach out for expert advice! My application generates Delayed::Jobs and I want to show users a visual indication of the job status as they progress. Let's assume ...

Is it possible for web browsers to accommodate various HTML5 pattern regexp functionalities?

A basic regular expression pattern was implemented in a payment form on our website for customers: <input type="text" pattern="(|\$)[0-9]*(|\.[0-9]{2})" title="Please enter a valid number in the amount field" required> This pattern ...

How to efficiently eliminate multiple entries with SREM in ioredis?

I am curious about the proper syntax for removing multiple entries using the SREM command. When I try this: const myKey = "myKey"; const entriesToRemove: string[] = ... this.redisClient.srem(myKey, entriesToRemove); I end up with: ReplyError: ...

The event listener $(window).on('popstate') does not function properly in Internet Explorer

$window 'popstate' event is not functioning properly in IE when using the browser back button. Here is the code snippet used to remove certain modal classes when navigating back. $(window).on('popstate', function(event) { event.pre ...

Derivations made from Input Variables

I'm working on a code snippet that allows users to enter invoice price and details, with the ability to input multiple values: However, I'm struggling to figure out where to start with the calculations. I'd like them to happen on every keyu ...

What could be causing my token to not save after registering a user?

I am currently facing an issue when submitting a registration form. While the user is successfully created, the token is not stored in localStorage, which prevents me from being redirected immediately to the app and forces me to log in again. Here is my R ...

Slider handle for Material UI in React component reaches the range value

In my application, I am using a range slider component from material-UI. The main page displays a data table with the fields: id, name, current price, new price. The current price for each item is fixed, but the new price will be determined based on the s ...

How to handle an unexpected keyword 'true' error when using the `useState` hook in React?

Trying to set the open prop of the MUIDrawer component to true on user click is causing an error stating "Unexpected keyword 'true'" import React, { useState } from "react"; import { withRouter } from "react-router-dom"; impo ...

Enhance shopping cart feature by allowing users to easily increase the quantity of an item in their basket

Having a challenge with the code functionality, I am looking to implement a logic that checks through my basket array of objects. If the ID exists, I want it to increase the quantity attribute of that specific entry instead of creating a new object. I atte ...

express-session is failing to maintain persistence and refusing to transmit a cookie to the browser

I am currently developing a web application using the MERN stack (React, Node.js, Express, and MongoDB). I have integrated express-session in my Node.js project, but for some reason, I cannot see the connect.sid cookie in the browser. Additionally, it appe ...

Generate an array containing multiple arrays with variable names

I am working on creating an array for each user and storing them in another array. Here is the code snippet I used for this: var arrays = []; var userCounter = 1; @foreach($eventUsers as $user) { arrays['arr' + userCounter] = []; userCount ...

Interacting with my Rails API through JavaScript requests

Exploring the world of Rails and diving into creating a basic rails-api. Currently facing an issue while trying to incorporate user addition to my model using a JavaScript request... Let's take a look at my HTML file named add-user.html: <script ...