3

I have an array stored in my local storage. It is dynamic. I'm storing the data along with an ID which gets incremented after every entry. User has an option of deleting, hence, I'm supposed to remove the corresponding element from the array. But, I want the ID to remain in ascending order. Ex:

var jsonObj = [{'id':'1','name':'Ray','email':'ray@gmail.com'},  
               {'id':'2','name':'Steve','email':'steve@gmail.com'},
               {'id':'3','name':'Albert','email':'albert@gmail.com'},
               {'id':'4','name':'Christopher','email':'chris@gmail.com'}]

I'm creating HTML divs for the above array. In case, Steve deletes his details, I want the array to be like:

var jsonObj = [{"id":1,"name":"Ray","email":"ray@gmail.com"},  
               {"id":2,"name":"Albert","email":'albert@gmail.com"},
               {"id":3,"name":"Christopher","email":"chris@gmail.com"}]

The following code doesn't work accordingly.

for (var i=0; i<jsonObj.length; i++) {
    //delete function is working fine.
    jsonObj[i].id--; 
    break;
    }
Venky
  • 350
  • 3
  • 15

9 Answers9

3

You could just iterate from the given index and decrement the id property.

function deleteItem(i) {
    array.splice(i, 1);
    while (i < array.length) {
        array[i].id--;
        i++;
    }
}

var array = [{ id: '1', name: 'Ray', email :'ray@gmail.com'}, { id: '2', name: 'Steve', email: 'steve@gmail.com' }, { id: '3', name: 'Albert', email: 'albert@gmail.com' }, { id: '4', name: 'Christopher', email: 'chris@gmail.com' }];

deleteItem(1);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

If you start from 0, then you do not even need the ID

Ray is the 0th element, Christopher is 3rd

delete Albert and Christopher is 2nd

var jsObj = [{'name':'Ray','email':'ray@gmail.com'},  
             {'name':'Steve','email':'steve@gmail.com'},
             {'name':'Albert','email':'albert@gmail.com'},
             {'name':'Christopher','email':'chris@gmail.com'}]
for (var i=0;i<jsObj.length;i++) {
  document.write("<br>ID"+(i+1)+": "+jsObj[i].name)
}
document.write("<hr/>");
jsObj.splice(2, 1); // Bye bye Albert
for (var i=0;i<jsObj.length;i++) {
  document.write("<br>ID"+(i+1)+": "+jsObj[i].name)
}

More information

Reindex javascript array / object after removing a key

Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • I did exactly the same thing, but I do have an edit option for users, where the user can edit any of the details. Uniqueness among the elements was lost and I'm ordered to use ID. Thanks for your response sir. – Venky Feb 21 '17 at 10:05
  • you can SHOW the id as the (i+1) in a loop – mplungjan Feb 21 '17 at 10:06
1

a very simplistic approach could be:

// the index of the deleted element
const delIndex = 2;

// reindex all entries starting from deleted one
for (var i=delIndex+1; i<jsonObj.length; i++) {
  jsonObj[i].id = i + 1;
}

The id basically corresponds with the array index anyway. So instead of trying to compute the id anew, we can just overwrite it with the respective index (+1 as you start with one and not zero like array indices).

Sirko
  • 72,589
  • 19
  • 149
  • 183
1

You just declare a new variable in your for loop which you will increment it and you assign this value as their id

for (var i=0, id=1; i<jsonObj.length; i++, id++) {

var jsonObj = [{'id':'1','name':'Ray','email':'ray@gmail.com'},  
               {'id':'2','name':'Steve','email':'steve@gmail.com'},
               {'id':'3','name':'Albert','email':'albert@gmail.com'},
               {'id':'4','name':'Christopher','email':'chris@gmail.com'}];


console.log(jsonObj);

jsonObj.splice(1, 1);


for (var i=0, id=1; i<jsonObj.length; i++, id++) {
 jsonObj[i].id = id;
}

console.log(jsonObj);
Beginner
  • 4,118
  • 3
  • 17
  • 26
1

for your requirements you have to use the splice method in the javascript

array.splice(index_you_wantto_delete,count)

ex:-jsonObj.splice(1,1);

The splice() method adds/removes items to/from an array,

Sandeep Bhaskar
  • 300
  • 2
  • 12
1

Here is a verbose solution explaining the process step by step

1- Delete the element

2 - Update the indexes if the element was found and deleted

/**
 * 
 * @param array list Your list
 * @param int elementID The id of the element you want to remove
 * @returns list The list with the element removed and the indexes rearanged
 */
var deleteElement = function (list, elementID) {
    var removedIndex = false;
    for (var index = 0; index < list.length; index++) {
        if (list[index]['id'] === elementID) {
            list.slice(index, 1);
            removedIndex = index;
            break;
        }
    } 
    if (removedIndex !== false) {
        //Get last id
        var lastElement = (removedIndex === 0) ? null : list[removedIndex - 1];
        // Set to 0 if the first element was removed
        var lastID = (lastElement === null) ? 0 : lastElement.id;
        for (var i = removedIndex; i < list.length; i++) {
            list[i].id = ++lastID;
        }
    } 
    return list;
};
beta-developper
  • 1,689
  • 1
  • 13
  • 24
1

Try the below method. Hope it works !!

// index of the deleted item
var itemDeleted = 2;

// create a for loop from deleted index till last
for (var i = itemDeleted-1; i < jsonObj.length; i++) {
   jsonObj[i].id = i+1;
}
1

You can do in pure js by using map

const jsonObj = [{
    'name': 'Ray',
    'email': 'ray@gmail.com'
  },
  {
    'name': 'Steve',
    'email': 'steve@gmail.com'
  },
  {
    'name': 'Albert',
    'email': 'albert@gmail.com'
  },
  {
    'name': 'Christopher',
    'email': 'chris@gmail.com'
  }
];

jsonObj.splice(1, 1);

const newObj = jsonObj.map((c, i) => ({
  name: c.name,
  email: c.email,
  id: i + 1
}));

console.log(newObj);
user93
  • 1,866
  • 5
  • 26
  • 45
0

Get the deleted index and assign it to the i value of for loop

for (var i=deletedIndex; i<jsonObj.length; i++) {
       jsonObj[i].id--;
    }
Dilip Belgumpi
  • 658
  • 4
  • 13