shanling shanling - 1 month ago 14
Javascript Question

How to correctly pass a whole array (not its items) as a parameter? (Javascript)

I have a set of divs that I store in an array that I then need to through and perform an action on everything except for the current iterated value. I have a fiddle here, which I think explains my situation properly.

Here is the function I'm using to select everything except for the value of (in this case)

n
.

const getRestOfArray = (array, n) => {
let arrayCopy = array.slice();
let index = arrayCopy.indexOf(n);
if (index > -1) {
arrayCopy.splice(index, 1);
return arrayCopy;
}
};


Am I doing something fundamentally wrong here? Thanks.

Answer

.indexOf() is not necessary. 2 is not an element of either array containing letters or DOM elements. You can call .splice() with n as first parameter, 1 as second parameter to return expected result.

const getRestOfArray = (array, n) => {
  let arrayCopy = array.slice();
  arrayCopy.splice(n, 1);
  return arrayCopy;
};

https://jsfiddle.net/a03kjwfy/1/