Jinendra Khobare
Jinendra Khobare

Reputation: 131

Removing elements from multi dimensional array using value in Javascript

I have a multidimensional array is :-

serialNos = [{id:'12',serial:'DAS245'},{id:'13',serial:'DAS246'},{id:'15',serial:'DAS247'}]

the ids and serials are random and i use push function to push them inside the array as i get those.

serialNos.push({id:'16',serial:'DAS248'});

Now, the thing is at times I have to remove elements from this array but all i get is serial not the id i.e., DAS248. How do I delete it in easy steps? I dont want to go thru iteration method as it takes too much memory and is not efficient. Also I want to restore order i mean indexes of serialNos in ascending order without any gaps.

NOTE : ids and serials both are unique

Platform : Javascript

Upvotes: 0

Views: 92

Answers (2)

reergymerej
reergymerej

Reputation: 2417

If you can use an object from the get go, that would be best (see @Travesty3 's answer). If you are stuck with your array, do something like this. You'll incur cost of indexing the array's objects only once rather than each time you want to find something.

var serialNos = [
  { id: 12, serial: 'DAS245' },
  { id: 13, serial: 'DAS246' },
  { id: 13, cereal: 'DAS249' },
  { id: 15, serial: 'DAS247' }
];

var moBetter = indexByKey(serialNos, 'serial');
console.log(moBetter.DAS246);

/**
* Given an array of objects, each with a unique attribute,
* this will return an object, indexed by those keys.
* @param {Object[]} arrOfObjects
* @param {String} key The unique identifier inside each object.
* @return {Object}
*/
function indexByKey (arrOfObjects, key) {
  var index = {},
    i = 0,
    max = arrOfObjects.length;

  // iterate through the array
  for (; i < max; i++) {

    // check to see if the object has the key
    if (arrOfObjects[i].hasOwnProperty(key)) {

      // make sure we haven't already indexed this key
      if (index.hasOwnProperty(arrOfObjects[i][key])) {
        console.error('Hey, wait.  These aren\'t unique!');
      } else {

        // If all is well, index this object by the key.
        index[arrOfObjects[i][key]] = arrOfObjects[i];
      }

    } else {
      console.error('This does not have the key, so it cannot be indexed.', arrOfObjects[i]);
    }
  }

  return index;
}

Upvotes: 1

Travesty3
Travesty3

Reputation: 14469

Assuming you don't have any repeated serial numbers, you could make serialNos an object instead of an array:

serialNos = {
    'DAS245': {
        id: 12,
        serial: 'DAS245'
    }
    // etc
};

This way, you can just delete the property using delete serialNos['DAS245'];.

With this method, there's no "sorting" this object, but when you iterate through it, you can use this solution.

Upvotes: 5

Related Questions