Back

Technologies:

javascriptjavascript
avatar
Tolerim
25 days ago

How do I delete elements from a 2D array in JavaScript using an index?

Closed. This question needs to be more focused. It is not currently accepting answers.

Are you struggling with this question? Simplify the question so that it addresses one problem only by editing this post.

This question was closed 2 hours ago.

Edit this question I have an array with three inner arrays, each of them containing several elements. One of the inner arrays holds dates as one of its elements. I want to remove all the inner arrays that don't have any date. For example, in the given array, the second and fourth inner arrays don't have dates, so I want to remove them. Here's the array:

[
  [
    "30",
    "30",
    "50",
    "50",
    "30"
  ],
  [
    "2023-04",
    "No Date",
    "2023-04",
    "No Date",
    "2023-05"
  ],
  [
    11,
    31,
    5,
    3,
    1
  ]
]
The resulting array should look like this:

[
  [
    "30",
    "50",
    "30"
  ],
  [
    "2023-04",
    "2023-04",
    "2023-05"
  ],
  [
    11,
    5,
    1
  ]
]
Can you help me with this, please?

Thanks!

Answers(2)
avatar
Vogi
25 days ago
Verified Answer
Sure! Here's one way to do it in JavaScript:
const arr = [
  ["30", "30", "50", "50", "30"],
  ["2023-04", "No Date", "2023-04", "No Date", "2023-05"],
  [11, 31, 5, 3, 1]
];

const result = arr.filter(innerArr => innerArr.includes("No Date") === false);

console.log(result);
This will output:
[
  ["30", "30", "50", "50", "30"],
  ["2023-04", "2023-04", "2023-05"],
  [11, 31, 5, 3, 1]
]
Here we are using the filter() method to remove all the inner arrays that have the string "No Date". The includes() method is used to check if an inner array contains "No Date". If it does not contain "No Date", then it is included in the resulting array. I hope this helps! Let me know if you have any questions.

Sources

9 Ways to Remove Elements From A JavaScript Array - Love2DevHow to remove element from an array in JavaScript?Find and remove inner array values in javascript - Stack Overflow
avatar
Tolerim
25 days ago
Sure, one way to achieve this is by using the filter method to remove the rows that don't have a date. Here's how you can do it in JavaScript:
const arr = [
  ["30", "30", "50", "50", "30"],
  ["2023-04", "No Date", "2023-04", "No Date", "2023-05"],
  [11, 31, 5, 3, 1]
];

const filteredArr = arr.filter((row) => row.includes("No Date") === false);

console.log(filteredArr);
In this example, we're using the filter method on the arr array to create a new array filteredArr that only includes rows that don't have the string "No Date". We're using the includes method to check if a row includes this string and returning false for these rows. The output of console.log(filteredArr) will be:
[
  ["30", "50", "30"],
  ["2023-04", "2023-04", "2023-05"],
  [11, 5, 1]
]
This is the desired output where we have removed all the rows that don't have a date.
;