Hello everyone who knows the filter()
method how I can tell if 2 or 3 values are the same in an array of n removes only one with each click ex an array [1,2,3,1, 3,4,5,3,1,1,4]
because with filter it will remove me every 1
or every 4
I would in fact like it to remove a 1 or a 4 for each click.
var butonAll = document.querySelectorAll("#supprimer");
console.log(butonAll);
butonAll[i].addEventListener("click", function (e) {
console.log("supprime moi");
const id = e.target.getAttribute("data-id");
objectJs2 = objectJs2.filter(function (obj, i) {
console.log(obj, i);
if (obj != id) return true;
});
objectJs = objectJs.filter(function (obj, i) {
console.log(obj[0]._id, i);
if (obj[0]._id != id) return true;
});
localStorage.setItem("object", JSON.stringify(objectJs));
localStorage.setItem("id", JSON.stringify(objectJs2));
console.log(id);
console.log(objectJs.length);
console.log(line2);
location.href = "panier.html";
if (objectJs.length === 0) {
localStorage.clear();
}
});
Array#filter will takes a function as a parameter that is executed against every elements of the array, independently.
If you want to only filter the first matching element, you could use an external variable to keep track of it:
let matched = false
let filtered = array.filter(x => {
if (matched) return true
if (x.id == id) {
matched = true
return false
}
return true
})
An alternative approach would be to find the index to remove using either indexOf
or findIndex
and to remove it with splice
let index = array.indexOf(id);
array.splice(index, 1);
Maybe you want this.
var arr = [1, 2, 3, 1, 3, 4, 5, 3, 1, 1, 4] console.log(arr); //Remove the first number one let has = arr.indexOf(1) //splice can remove data if receive negative numbers if (has > -1) arr.splice(has, 1) console.log(arr);
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.