Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I move an array record to 0 index and 0 index record to next index and so on

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

  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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading