You can use splice for that purpose. To play off of your example:
var animals = [‘pigs’, ‘goats’, ‘sheep’];
animals.push(‘cows’)
// now, take out goats, the second item in the array
animals.splice(1,1);
console.log('First item in array after goats was removed: ’ + animals[0]);
console.log('Second item in array after goats was removed: ’ + animals[1]);
console.log('Third item in array after goats was removed: ’ + animals[2]);
A common way to do this is to obtain the index of the item to remove with the indexOf function. Now that you know the index of it, apply that variable to the splice function.
let index = animals.indexOf(‘goats’);
animals.splice(index,1);
Hi Shan. I’m trying to do the same. I’ve added in the array, but I’m not sure how to remove the item. I’m using a checkbox to see whether to add or remove. Can you explain a little bit? My code:
let secondRepeaterData = [];
function selectItem() {
let itemToAdd = {};
let sumTotal = 0;
$w("#selectItem").onChange((event) => {
const $item = $w.at(event.context);
if ($item("#selectItem").checked) {
let finalPrice = $item("#price").text * $item("#dropdown1").value;
$item("#ifMarked").text = finalPrice.toString();
let id1 = $item('#title').text;
let id11 = id1.replace(/\s/g, "");
let price = $item('#price').text;
let marked = $item('#ifMarked').text;
let qty = $item('#dropdown1').value;
itemToAdd = {
"_id": id11,
"price": price,
"qty": qty,
"title1": id1,
"ifMarked": marked
};
secondRepeaterData.push(itemToAdd);
console.log(secondRepeaterData);
} else //if (!($item("#selectItem").checked))
{
$item("#ifMarked").text = "0";
let id1 = $item('#title').text;
let id11 = id1.replace(/\s/g, "");
async function removePType($item1, params) {
removeByKey({
key: id11,
value: id11
});
}
function removeByKey(params) {
console.log("wo");
secondRepeaterData.some(function (item, index) {
if (secondRepeaterData[index][params.key] === params.value) {
secondRepeaterData.splice(index, 1);
console.log(secondRepeaterData);
}
});
}
}
});