skip to Main Content

im working my way through the odin project and looking at for loops and different methods. Im trying to find a way to pass this test :

test('removes multiple of the same value', () => {
expect(removeFromArray([1, 2, 2, 3], 2)).toEqual([1, 3]);
});

I know you can remove a duplicate using filter and Sets but how do i remove both the 2’s in the array so i end up with [1, 3]

I know this is probably simple but its just where im upto at the moment.

3

Answers


  1. Chosen as BEST ANSWER

    Ok I came up with this :

    const array = [1, 2, 2, 3];
    
    function removeFromArray(){
     
    let uniqueArray = [...new Set(array)];
    uniqueArray.splice(1,1);
    return uniqueArray;
    
      
    }
    
    removeFromArray();
    

    It passed the test.Not sure its the right way to do things but it works and i understand it so thats a bonus.

    Jabaa, thanks for your prompt. Sometime with JS I just cant think straight.


  2. You can iterate twice over the array. In the first iteration, you count the occurrences of the elements and in the second iteration you remove elements with occurrence > 1.

    Login or Signup to reply.
  3. function removeFromArray(arr) {
    
    if(!arr ||!arr.length){
    return [];
    }
    const remElem = {};
    
    const all = arr.reduce((all,cur) => {
    if(!all[cur]) {
    all[cur] = true;
    } else {
    remElem[cur] = true;
    }}, {}) ;
    
    return Object.keys(all).filter(cur => !remElem[cur]);
    } 
    

    Wrote on cellphone, cant test, please test, it should work 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search