Ways to eliminate specific items from the inner array using JavaScript

Let's consider an array with values: [[10, 20, 30, 20, 50], [40, 50, 60, 20, 20], [70, 80, 90, 20, 20], [70, 80, 90, 20, 20]];

In this case, the task is to remove all elements that equal 50 from the subarrays.

The desired resulting array would be: [[10, 30, 20], [40, 60, 20], [70, 90, 20], [70, 90, 20]];

An attempted solution using a nested loop to iterate through and delete elements where value equals to 50 was not successful.

for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array[i].length; j++) {
        if (array[i][j] == 50) {
            array[i].splice(j, 1);
         }
     }
 }

Answer №1

Make sure to gather all the unnecessary indexes before proceeding with the return statement.

const
    numbers = [
        [10, 20, 30, 20, 50], 
        [40, 50, 60, 20, 20], 
        [70, 80, 90, 20, 20], 
        [70, 80, 90, 20, 20]
    ],
      
    indicesToRemove = numbers.reduce(
        (result, array) => array.map((value, index) => value === 50 ? false : result[index] ?? true),
        []
    ),
    
    filteredNumbers = numbers.map(array => array.filter((_, index) => indicesToRemove[index]));

filteredNumbers.forEach(array => console.log(...array));

Answer №2

let numbers = [[10, 20, 30, 20, 50], [40, 50, 60, 20, 20], [70, 80, 90, 20, 20], [70, 80, 90, 20, 20]];

const cleanNumbers = numbers.map(group => [...new Set(group.filter(num => num !== 50))])

// cleanNumbers = [[10, 30, 20], [40, 60, 20], [70, 80, 90, 20], [70, 80, 90, 20]];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Two approaches to discovering a set of items within an array that yield contrasting outcomes

Two different approaches are being used to solve this problem. "Determine a pair of numbers in an array that add up to a specific value" However, these methods are yielding distinct outcomes. What could be the reason behind this discrepancy? One method i ...

problem encountered while attempting to transmit data to multer in React

I was attempting to upload an image to the backend using Multer. I have reviewed the backend code multiple times and it appears to be correct. Could there be an issue with my front-end code? Here is a POST code snippet: const response = await fetch(' ...

Execute the JavaScript callback

I am encountering an issue when trying to pass an anonymous function as a callback and call it. I seem to be missing something simple, because I keep getting the error 'Uncaught type error - callback is not a function'. Here is what I am attempti ...

If a user touches outside of the scroll component on mobile, the scroll in the popup freezes

I have a webpage that includes two scrollable lists: one in the main body and another in a popup window. To prevent scrolling of the main body when the user scrolls inside the popup, I am using a standard solution recommended in this Stack Overflow post ab ...

"Seeking a method to identify a single unsorted element within an array that is otherwise sorted in the C programming language

Here are three scenario cases where the elements are mostly sorted except for one element: {-17, -5, -5, -2, 1, 17, 289, 17, 17, 395} | The out-of-place element is at index 6. {289, 17, 17, 17, 100, 250, 300, 1000, 5000} | The out-of-place element is at ...

Dragging elements with jQuery to move them outside of a side panel

For a hidden panel, I am utilizing the script mentioned below. I have listed some boxes in the panel and attempted to drag them and drop them onto a workspace. This is a demonstration that works with HTML5. <a id="simple-menu" href="#sidr">Jobs< ...

Is it possible to utilize .show() or .hide() with a binary switch instead of a traditional if statement?

Is it feasible to achieve something similar to this using jQuery? $('#MyDiv').show((MyVar==2?1:0)); // 1=show, 0=hide. If not, I will need to repeat this code in multiple places. if(MyVar==2?1:0){$('#MyVar').show();}else{$('#MyV ...

Exploring options for accessing Google Maps API on iPhone without using UIWebView for processing JavaScript

I need to retrieve data from Google Maps using JavaScript, without using a webview. For example, I have two points (lat,lng) and I want to use the Google Maps API to calculate the driving distance between them. Essentially, I want to utilize the Google Ma ...

Encountering difficulties when attempting to store files using mongoose in a node express.js program

I encountered an error while attempting to save a document to the MongoDB using Mongoose in my Node Express.js project. Below is the code snippet: exports.storeJob = async (req, res, next) => { const { name, email, password, title, location, descri ...

What is the reason that PHP is not functioning properly?

I have a website with two pages. On the first page, there are select boxes and a send button. When the user selects their options from the boxes and clicks send, they are taken to the second page where their choices are displayed. Date Selection Page < ...

Facing an issue in React-Native where unable to navigate to the second screen

I hope you don't mind the length of my query, as this happens to be my debut here and I am really eager to unravel the mysteries surrounding my code conundrum. Your assistance in this matter would be greatly appreciated. Could someone please lend me ...

What is the quickest way to populate a Structure with values?

I am currently working on my program in Visual Studio 2013 using Standard C. It's taking up four lines of code to fill Fach[0] with the values {"Analysis 1", "AN 1", 0, 0.0667}. I really wish there was a more efficient way to accomplish this without ...

Checkbox in Angular FormGroup not triggering touched state

There seems to be an issue with the Angular form when checking if the form is touched, especially in relation to a checkbox element. Despite the value of the checkbox changing on click, I am seeing !newDeviceGroup.touched = true. I'm not quite sure wh ...

Dynamic form name validation in Angular is crucial for ensuring the accuracy and

When it comes to validating a form in Angular, I usually use the ng-submit directive like this: <form name="formName" ng-submit="formName.$valid && submitForm()"></form> This method works well for forms with predefined names that I se ...

Assigning random classes from a pool of just 3 variables to over 20 different div elements

I have a total of 20 divs and three different hover effect classes. I would like to randomly assign one of these three hover effects to each div. The JavaScript code I am using is: <script> $(document).ready(function () { viewClasses = 3; randomNum ...

Deleting a li element within an AJAX response function can be accomplished by targeting the specific

I am attempting to remove the li element that is the parent of the clicked a element. Here is the code I am using: function vanish(id_arg){ $.ajax({ url: "/vanish/", type: "POST", data: {id_to_delete: id_arg}, ...

Is there a way to confirm that the format of yyyy-mm-dd hh:mm:ss is valid

I came across this code snippet for validating dates in the format of mm/dd/yyyy or mm-dd-yyyy, but I need to validate yyyy-mm-dd hh:mm:ss as well. How can I make sure that today's date is before the selected date using the yyyy-mm-dd hh:mm:ss format? ...

Creating a React Mui TextField specifically for currency input on iPhone Safari: ensuring that only digits are allowed

I have implemented a Mui TextField component for currency input that displays only the numeric keyboard in the Safari browser. However, I want to restrict users from pasting literal strings into the field and ensure that only currency number inputs are al ...

The useEffect function is failing to execute, leading to an issue with an undefined variable

Attempting to retrieve a specific string with the help of useRouter, then utilizing that same string to access a particular document from Firebase is my current goal. This sequence of actions is supposed to take place within the confines of the useEffect f ...

Need to obtain the stack trace from the catch block in a request-p

Currently, I am utilizing the 'request-promise' library in my node-js application for making API calls. However, I am facing challenges in obtaining the correct call stack from the 'catch' function. Upon experimenting with it, I discove ...