简体   繁体   中英

Remove an item from an array by value, but leave the duplicates of that item

I have a very simple array like this:

array = [1, 1, 6, 7, 9, 6, 4, 5, 4];

I need to be able to remove a value, but I need to remove only one value if there's duplicate values. So if I remove the value 6 , the array should become:

array = [1, 1, 7, 9, 6, 4, 5, 4];

The order of which one gets removed doesn't matter, so it could be the last no. 6 or the first no. 6. How can I do this?

Edit I see there's a lot of confusion about why I need this, which results in incorrect answers. I'm making a Sudoku game and when a user inserts a number in a cell, the game has to check if the chosen number already occupies space in the same row or column. If so, the number of that specific row/column is added to this array. However, when a user fixes a mistake, the number of the row/column should be removed. A user can, however, make multiple mistakes in the same row or column, which is why I need to retain the duplicates in the array. Otherwise, users can make multiple mistakes in a row/column, and only fix one, and then the code will think there are no errors whatsoever anymore.

Hope this makes things more clear.

Try to get the index of your item with indexOf() and then call splice()

 let array = [1, 1, 6, 7, 9, 6, 4, 5, 4]; let index = array.indexOf(6); array.splice(index,1); console.log(array); 

You can use Array.prototype.findIndex to find the first index at which the element to be removed appears and then splice it.

Also you can create a hastable to ascertain that we remove only if a duplicate is availabe - see demo below:

 var array = [1, 1, 6, 7, 9, 6, 4, 5, 4]; var hash = array.reduce(function(p,c){ p[c] = (p[c] || 0) + 1; return p; },{}); function remove(el) { if(hash[el] < 2) return; array.splice(array.findIndex(function(e) { return e == el; }), 1); } remove(6); remove(7); console.log(array); 

 var array=[1, 1, 6, 7, 9, 6, 4, 5, 4], removeFirst=function(val,array){ array.splice(array.indexOf(val),1) return array; }; console.log(removeFirst(6,array)); 

If order of removed element (not elements!) isn't important, you can use something like this:

 array = [1, 1, 6, 7, 9, 6, 4, 5, 4]; function remove_if_dupe(elem, array) { dupes=[]; for(i=0;i<array.length;i++) { if(array[i] === elem) { dupes.push(elem); } } if(dupes.length>1) { //is duplicated array.splice(array.indexOf(elem), 1); } return array; } console.log(remove_if_dupe(6,array)); 

This should keep unique elements, hopefully.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM