Home > Software engineering >  Unabled to remove items from an array
Unabled to remove items from an array

Time:07-15

I am trying to run npm test on a function. I ran 7th test where all are successful except the 6th. I havent tried the 7th though. I tried various solutions but it still don't work. My last resort is to use spread syntax or the rest parameters. I tried it too but it doesn't work. Please help.

const removeFromArray = function(para1,  para2,  para3,  para4) {
    let i = 0;
    while (i < para1.length) {
        if (para1[i] === para2 || para1[i] === para3  || para1[i] === para4) {
            para1.splice(i, 1);
        } else {
              i;
        }
    }
    return para1;
}

removeFromArray( [1, 2, 3, 4], 3);

removeFromArray( [1, 2, 3, 4], 3, 2);

removeFromArray (["hey", 2, 3, "ho"], "hey", 3);

----------------------------------Jest test-------------------------------------------

describe('removeFromArray', () => {
  test('removes a single value', () => {
    expect(removeFromArray([1, 2, 3, 4], 3)).toEqual([1, 2, 4]);
  });
  test('removes multiple values', () => {
    expect(removeFromArray([1, 2, 3, 4], 3, 2)).toEqual([1, 4]);
  });
  test('ignores non present values', () => {
    expect(removeFromArray([1, 2, 3, 4], 7, "tacos")).toEqual([1, 2, 3, 4]);
  });
  test('ignores non present values, but still works', () => {
    expect(removeFromArray([1, 2, 3, 4], 7, 2)).toEqual([1, 3, 4]);
  });
  test('can remove all values', () => {
    expect(removeFromArray([1, 2, 3, 4], 1, 2, 3, 4)).toEqual([]);
  });
  test('works with strings', () => {
    expect(removeFromArray(["hey", 2, 3, "ho"], "hey", 3)).toEqual([2, "ho"]);
  });
  test.skip('only removes same type', () => {
    expect(removeFromArray([1, 2, 3], "1", 3)).toEqual([1, 2]);
  });
});

CodePudding user response:

I cant reply comment since I dont have 50 reputations :(

  • Expected - 1, Received 3
  • Array [ ], Array [ , 4, ]

CodePudding user response:

Your function is good but when it's comparing arrays it returns false:

[2, "ho"] == [2, "ho"] -> false 
[2, "ho"] === [2, "ho"] -> false
  • Related