Last Updated: April 20, 2021
·
243
· shinjukudev

Remove Element (JS Algorithm)

This function will remove all instances of an integer from an array of integers. First version uses a second array to accomplish this. Second one uses a nested for-loop. Anyone have a good solution that preforms the operation in place (i.e. not using a second array) and without the dreaded nested-for loop?

Version 1: Solved using second array

var int = 3;
var arr = [3,3,3,3,3];

function removeElement1(int, arr) {

  if(typeof int != 'number' && typeof arr != 'object') {
    return false;
  }

  var output = [];

  for(var i = 0, len = arr.length; i < len; i++) {

    if(arr[i] != int) {
      output.push(arr[i]);
    }

  }

  arr = output;

  return arr;

}

console.log(removeElement(int, arr));

Version 2: Solved using nested for-loop

var int = 3;
var arr = [3,3,3,3,3];

function removeElement2(int, arr) {

  if(typeof int != 'number' && typeof arr != 'object') {
    return false;
  }

  for(var i = 0, len = arr.length; i < len; i ++) {

    for(var j = 0; j < len; j++) {

      if(arr[j] === int) {
        arr.splice(j, 1);
      }

    }

  }

  return arr;

}

console.log(removeElement2(int, arr));

4 Responses
Add your response

Your first function returns the length of the array, so I'm not quite sure if that's what you intended; however, here is a way without a loop.

var int = 3;
var arr = [3,3,3,3,3];
function removeElement(int, arr) {
  if(typeof int != 'number' && typeof arr != 'object') {
    return false;
  }
  // build a regexp that will account for commas on either side of the searched number so we can join it and replace all instances of the number
    var pattern = new RegExp(int.toString() + "|," + int.toString() + "|" + int.toString() + ",", "g");
    arr = arr.join().replace(pattern, "").split(",");
  if (arr.join() == "")
  {
  // this is to account for an array with just one element of an empty string
      return new Array();
  }
  else
  {
  // return the array that is split
      return arr;
  }
}

alert(removeElement(int, arr).length);
over 1 year ago ·

@jeffcheung Thanks again for the great feedback. I learned a new way of working with reg-ex patterns from your example.

Yes, the return arr.length was unintended. Fixed the typo now

over 1 year ago ·

I noticed that if the first integer in the array matches the integer to be removed, for instance:

var int = 3;
var arr = [3,1,2,3];

The array will be returned as follows, with an empty string at index arr[0]:

["","1","2"]

This case is also different than expected:

var int = 3;
var arr = [2,2,23333,2];

returns:

["2","2","2","2"]

I was expecting the returned array to equal 2,2,23333,2] So I think this is simply a matter of a different interpretation of the problem.

over 1 year ago ·

Hope it helps! :)
js function removeInstances(arr, elem){ return a.filter(function(i){ return (i !== elem) }) }

over 1 year ago ·