0

I have a requirement to find specific record from array and move that to first position (0 index) and 0 index should move to next index and so on.

I do not want to remove or duplicate any record from array. This is what I have tried, it gives error splice is not defined

 var record = data.find(x => x.CodeLovId == existingGridCellItem);
           if (record !== null) {
               data.remove(record)
               data.splice(0, 0, record);
                               
            }

And below code duplicates records and removes existing

var record = data.find(x => x.CodeLovId == existingGridCellItem);
               if (record !== null) {
                   data[0] = record                                  
                }

Ex -

arr1 = ['YES', 'NO', 'OK']
Item to move ['NO']
Ans - arr1 = ['NO', 'YES', 'OK']

How can I do it ?

R15
  • 13,982
  • 14
  • 97
  • 173
  • 2
    Is `data` a proper array? It's strange you're getting that error if so. Arrays don't have a native `remove` method so I expect it's something different. – cmbuckley Feb 17 '23 at 13:11

2 Answers2

2

You need indices for manupulating arrays. To get only an item does not work with your code.

Instead

  1. get the index of the wanted item to be moved to top,
  2. check if index is in array and
  3. unshift spliced item.

const
    array = [1, 2, 3, 4, 5],
    index = array.findIndex(v => v === 4);

if (index !== -1) array.unshift(...array.splice(index, 1));

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    If the value we are looking for is not available in the list, It'll still change the order. `array.findIndex(v => v === 24);` Output: `[5, 1, 2, 3, 4]` – Rahul Sharma Feb 17 '23 at 13:17
  • if values not in array, you need a sanity check in advance. plkease see edit. – Nina Scholz Feb 17 '23 at 13:20
  • 1
    Why are you answering questions that are clearly duplicates? – Dexygen Feb 17 '23 at 14:09
  • @Dexygen, op's problem is not only to add an item to the front of an array, but also to find the index fro removing the item. the pupe target is only addressing the adding in front of the array, but not the rest. – Nina Scholz Feb 17 '23 at 14:47
  • 1
    You are being disingenuous, the OP had already demonstrated they knew the steps before unshift. – Dexygen Feb 17 '23 at 17:05
2

You can use splice and unshift, to remove value from the index and to the first position.

const list = [1, 2, 3, 4, 5];
const record = 31;
const index = list.indexOf(record);
if (index !== -1) {
  list.splice(index, 1);
  list.unshift(record);
}

console.log(list);
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37