Dynamically remove arrays from multidimensional array

Dear all,

I am developing a webshop in which (amongst others) I will sell radiators. In the webshop I will let users select the radiators on two dimensions via dropdown menu’s: Length and Width, and add a description in what room to place the radiator.

The page contains a table, with four columns:

  1. Length
  2. Width
  3. In what room to place the radiator
  4. A remove button

For each radiator purchased, a new row is added to the table.

I also have a multidimensional array shoppingCartRadiators which contains all radiators purchased. E.g,
[ [200, 30, “kitchen”],
[150, 60, “living room”],
[90, 40, “bathroom”],
[120, 60, “bedroom”]]

I created the following function to add a radiator, if a person clicks on the Purchase button:

function AddNewRadiator() {
var table = document.getElementById(“radiator_table”);
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);

let newRadiator=;

const newButton = document.createElement(‘button’);
newButton.textContent = “Remove”;
newButton.addEventListener(“click”, function () {
this.parentElement.parentElement.remove();
})

cell1.innerHTML = document.getElementById(“Length”).value ;
cell2.innerHTML = document.getElementById(“Width”).value ;
cell3.innerHTML = document.getElementById(“which_room”).value ;
cell4.appendChild(newButton);

newRadiator = [document.getElementById(“Length”).value,
document.getElementById(“Width”).value,
document.getElementById(“which_room”).value
] ;
shoppingCartRadiators.push(newRadiator);
}

The function works perfectly to add or remove rows from the table. It also works to add arrays to the multidimensional array. However, how should I remove an array from the multidimensional array? The problem is that first a user might remove the Kitchen radiator, and then the Bathroom radiator.

Kind regards and many thanks

Hi,

  1. Please format your code when you post it. You were told how to do this here.
  2. I would seriously consider using an array of objects as your data structure. This was suggested here.

You can use Array.filter.
Ref.: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Here is an example:

let radiators = [
  [200, 30, 'kitchen'],
  [150, 60, 'living room'],
  [90, 40, 'bathroom'],
  [120, 60, 'bedroom']
];

radiators = radiators.filter(radiator => ! radiator.includes('kitchen') );
console.log(radiators);

HTH

3 Likes

Hi James,

Many thanks, it works! Apologies for the code formatting. I will be careful a next time.

Kind regards

1 Like