0

Like in title, can I modify array passed as an argument? (without using return)

function arrayElementsRemove(array, element) {
    array.filter(item => item != element);
}

and then

it('should remove items from array', () => {
    var array = [1,2,2,3];
    arrayElementsRemove(array, 3);
    expect(array).to.equal([1,2,2]); // fails, array still equals [1,2,2,3]
});
Paweł Andruszków
  • 8,213
  • 1
  • 12
  • 11
  • 2
    Yes, you definitely can. You could probably have figured that out with a quick test in your browser developer console or Node.js. – Pointy Jul 04 '17 at 22:16

1 Answers1

3

Arrays are passed as reference. Your issue is that Array.filter does not change the original array, it returns a new one.

Instead of Array.filter, you should do a loop from length-1 to 0, and when element === array[i] use Array.splice to remove the item.

Your arrayElementsRemove function should look like this:

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

function arrayElementsRemove(array, element) {
    for (var i = array.length-1; i >= 0; i--) {
        if (array[i] === element) {
            array.splice(i, 1);
        }
    }
}

arrayElementsRemove(arr, 3);

console.log(arr);
Washington Guedes
  • 4,254
  • 3
  • 30
  • 56