skip to Main Content

I have an array of objects with a position property along with other properties like this:

[{position: 1, ...otherProperties}, ...otherObjects]

In the frontend, the objects are displayed and sorted by their position.

I am looking for JavaScript functions to perform the following operations:

  1. Insert a new object at a specified position (e.g., before the element with position: 1) and update the positions of the other elements accordingly (e.g., previous position: 1 element will now be position: 2).
  2. Delete an object from a specified position and update the positions of the remaining elements accordingly.

I am struggling with the creation of these functions

2

Answers


  1. You can create two functions addElement and removeElement to add or delete elements in your array, while ensuring the positions are sorted correctly. For example:

    function addElement(arr, newPosition, newElement) {
      // Add a new element at the given position
      newElement.position = newPosition;
      arr.push(newElement);
    
      // Sort the array by position
      arr.sort((a, b) => a.position - b.position);
    
      // Update the position of elements
      arr.forEach((item, index) => {
        item.position = index + 1;
      });
    
      return arr;
    }
    
    function removeElement(arr, positionToRemove) {
      // Remove the element from the given position
      arr = arr.filter(item => item.position !== positionToRemove);
    
      // Update the remaining elements' positions
      arr.forEach((item, index) => {
        item.position = index + 1;
      });
    
      return arr;
    }
    

    Usage:

    let array = [
      { position: 1, prop: "a" },
      { position: 2, prop: "b" },
      { position: 3, prop: "c" },
    ];
    
    let newArray = addElement(array, 1, { prop: "d" });
    console.log(newArray);
    
    newArray = removeElement(newArray, 3);
    console.log(newArray);
    
    Login or Signup to reply.
  2. You need a method that parse all items of your array and set the new position to all of it.

    function fixPosition(arr) {
      arr.map((o, i) => o.pos = i+1)
      return arr
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search