Gustavo Rodrigues
Gustavo Rodrigues

Reputation: 61

Remove a specific amount of elements in the array

i want to specify how many 1 elements I want to remove within that array:

const array = [1, 1, 2, 3, 1, 5];

I tried like that:

const array = [1, 1, 2, 3, 1, 5];

const i = array.indexOf(1);
if (i > - 1) {
  array.splice(i, 1);
}

but this remove just first element 1 in array

Upvotes: 2

Views: 107

Answers (4)

Karl Lopez
Karl Lopez

Reputation: 1099

Try this, Array.prototype.filter will create a new array and will not mutate or change the array on which it is called.

const arr = [1, 1, 2, 3, 1, 5];

const newArr = arr.filter((item) => item !== 1);
console.log(newArr);

const removeArrayItem = (array, item) => array.filter((i) => i !== item);
console.log(removeArrayItem([1, 2, 2, 2, 2, 3, 4, 5], 2));
console.log(removeArrayItem([1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 8, 8], 8));

// or using reduce
const removeDuplicateItem = (arr, itemToRemove, count) =>
  arr.reduce(
    (accumulator, currentItem) => {
      if (
        accumulator.count &&
        accumulator.count > 0 &&
        currentItem === itemToRemove
      ) {
        accumulator.count -= 1;
        return accumulator;
      }

      accumulator.result.push(currentItem);

      return accumulator;
    },
    {
      count,
      result: [],
    },
  ).result;

// This will remove 5 number twos
console.log(removeDuplicateItem([1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 8, 8], 2, 5));

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386654

You need to iterate the count and check if an item is available for removing.

function remove(array, value, count) {
    while (count--) {
        const i = array.indexOf(value);
        if (i === -1) break;
        array.splice(i, 1);
    }
}

const array = [1, 1, 2, 3, 1, 5];

remove(array, 1, 2);

console.log(array);

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28414

You can use a while loop to remove N number of elements with this value:

const removeNInstancesOfX = (array, n, x) => {
     let i = null, count = 0, arr = [...array];
     while ((i = arr.indexOf(1)) !== -1 && count++ < n)
          arr.splice(i, 1);
     return arr;
}

let array = [1, 1, 2, 3, 1, 5];
     
array = removeNInstancesOfX(array, 2, 1);

console.log(...array);

Upvotes: 1

zb22
zb22

Reputation: 3231

If you want to remove only the amount of 1s you specify,
You can use a for loop with 2 conditions, one for array size and the second for the number of times 1 was found and removed.

const array = [1, 1, 2, 3, 1, 5];
const counter = 2;

for(let i = 0 , n = 0; i < array.length && n < counter; i++) {
  if(array[i] === 1) {
    array.splice(i, 1);
    i -= 1;
    n++;
  }
}

console.log(array);

Upvotes: 1

Related Questions