2

I have an array in JavaScript and I need to find a specific element and remove it. I tried with splice() and findIndex() and it's not supported in JSEclipse nor in IE9. I used splice() and find() and it doesn't work in IE9.

There are 2 points why my question is not a duplicate: (1) My array is an array of objects so using indexOf() does not apply. (2) Support in IE9 is prerequisite for my solutions.

I would appreciate any assistant.

My array:

var portingOptions = [
   {
      name: 'print',
      iconClass: 'faxBlue'
   },
   {
      name: 'pdf',
      iconClass: 'pdfBlue'
   },
   {
      name: 'exportToCcr',
      iconClass: 'documentBlue'

   },
   {
      name: 'message',
      iconClass: 'secureMessageBlue'
   },
   {
      name: 'email',
      iconClass: 'emailBlue'
   }
];

My code with splice() and find():

if (myParameters.removeEmailField) {
   portingOptions.splice(portingOptions.find(function(element) {
      return element.name === 'email';
      })
   );
}

Does anyone know of a solution that will work on IE9?

Binyamin Regev
  • 799
  • 2
  • 15
  • 26
  • You can use polyfill for `filter`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Polyfill – nbokmans Jan 17 '19 at 09:24
  • Possible duplicate of [How do I remove a particular element from an array in JavaScript?](https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript) – Manuel Espinosa Jan 17 '19 at 09:26
  • It's not a duplicate as I can't use `indexOf()` - my array is an array of objects and using `indexOf()` does not apply to my question. – Binyamin Regev Jan 17 '19 at 12:15

2 Answers2

0

You could take a while loop, instead of find, which is not implemented.

If you like to remove more than one, remove break statement.

var index = array.length;

while (index--) {
    if (array[index].name === 'email') {
        array.splice(index, 1);
        break;
    }
}
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
0

You can use jQuery methods $.grep() to replace your Array.find()

Array.splice() instead seems to be supported from IE 5.5

There is also a nice polyfill that should work on IE9:

Array.prototype.find = Array.prototype.find || function(callback) {
  if (this === null) {
    throw new TypeError('Array.prototype.find called on null or undefined');
  } else if (typeof callback !== 'function') {
    throw new TypeError('callback must be a function');
  }
  var list = Object(this);
  // Makes sures is always has an positive integer as length.
  var length = list.length >>> 0;
  var thisArg = arguments[1];
  for (var i = 0; i < length; i++) {
    var element = list[i];
    if ( callback.call(thisArg, element, i, list) ) {
      return element;
    }
  }

Ref:https://github.com/jsPolyfill/Array.prototype.find/blob/master/find.js

Mosè Raguzzini
  • 12,776
  • 26
  • 36