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
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));
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);
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);
If you want to remove only the amount of 1
s 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.