Eliminating a sub-array within an array

This is the issue at hand: A function named filteredArray has been created. It takes two arguments - arr, a nested array, and elem. The purpose of this function is to return a new array by filtering out any nested arrays within arr that contain the specified elem. To achieve this, a for loop is utilized in the function.

The specific problem with the code: Upon examining my solution closely, I have noticed an interesting behavior. The function works as intended only when the nested loop starts with the number 3. If this position is changed (such as in the 2nd and 4th nested arrays), the function fails to produce the expected outcome.

function filteredArray(arr, elem) {
  let newArr = [];
  let myNestedArray;
  // Only change code below this line
  for (let i = 0; i < arr.length; i++) {
    myNestedArray = arr[i];
    for (let j = 0; j < myNestedArray.length; j++) {
      if (myNestedArray[j] === elem) {
        console.log(`Main arr is => ${arr}`);
        console.log(`Nested array is =>  [${myNestedArray}]`);
        console.log(`Elem is => ${elem}`);
        arr.splice(arr.indexOf(myNestedArray), 1);
        myNestedArray = [];
        console.log(`#######`);
    }
}
}
newArr.push(arr);
  // Only change code above this line
  return newArr;
}

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

Answer №1

  • Declare a boolean variable named isValueFoundInSubArray
  • If the flag is false when reaching the end of a subArray, add it to a new array

Snippet :

  function filteredArray(arr, elem) {
    let newArr = [];
    let myNestedArray;
    // Only modify code below this line
    for (let i = 0; i < arr.length; i++) {
      myNestedArray = arr[i];
      let isValueFoundInSubArray = false;
      for (let j = 0; j < myNestedArray.length; j++) {
        if ((!isValueFoundInSubArray) && myNestedArray[j] === elem) {
            isValueFoundInSubArray = true;
        }
        if ((j === myNestedArray.length - 1) && !isValueFoundInSubArray) {
         newArr.push(myNestedArray)
        }
      }
    }
    // Only modify code above this line
    return newArr;
  }

Answer №2

When a house is removed from the presentation, it causes the circle to skip over the last house being considered, resulting in the inability to complete the task at hand. Using a foreach loop is a better approach in this scenario.

function filteredArray(arr, elem) {
  const newArr = [];
  // Make changes only below this line
  arr.forEach((myNestedArray) => {
    myNestedArray.forEach((i) => {
      if(i===elem){
        const loc = myNestedArray.indexOf(i)
        myNestedArray.splice(loc,loc+1)
        console.log(`Main arr is => ${arr}`);
        console.log(`Nested array is =>  [${myNestedArray}]`);
        console.log(`Elem is => ${elem}`);
        console.log(`#######`);
      }
      if(!myNestedArray.includes(elem)){
        return ;
      }
    });
    arr.push(myNestedArray);
    arr.shift();
  });
  newArr.push(arr);
  // Make changes only above this line
  return newArr;
}

console.log(
  filteredArray(
    [
      [3, 2, 3],
      [1, 6, 3],
      [3, 13, 26],
      [19, 3, 9],
    ],
    3
  )
);

Answer №3

If you're looking to delete data from a nested array in JavaScript, one approach is to utilize the Splice method. This method allows you to specify the index of the element within the nested array that you want to remove.

Sample Code:

let mainArray= [[1, 2], [3, 4, 5], [6, 7, 8, 9]];
let nestedIndex= 3;

mainArray.forEach((array, index) => {
  let nestedIndex= array.indexOf(nestedIndex);
  if (nestedIndex!== -1) {
    array.splice(nestedIndex, 1);
  }
});

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

JavaScript: Modify the dropdown class with a toggle option

Hi there, I'm currently facing a small issue and I could really use some assistance. I have a dropdown menu with two selection options - "green" and "blue", and I need to toggle a class based on the selected option. If you'd like to take a look, ...

If I change the request mode to 'no-cors' in my Firebase cloud function, how will it impact the outcome?

After encountering an issue with the Firebase inbuilt password reset functionality, I created a Firebase function to handle OTP verification and password changes based on the correctness of the OTP. The function is designed to validate the OTP provided, ch ...

There appears to be an issue with 'session' being undefined in this JS/Express/Redis setup for session storage

I've been experimenting with using redis for sessions in my express app. This is what I'm doing: server/auth.js import express from 'express'; import uuid from 'uuid'; const router = express.Router(); router.route(' ...

The filter and search function in the table is malfunctioning

Recently, I developed a page designed for saving actors in an array and displaying them in a table. However, my attempt to add a search feature by name failed. If anyone has encountered a similar issue before and knows how to resolve it, please share your ...

Using React to Dynamically Display JSON Data as HTML

Struggling to incorporate HTML rendering from JSON data into my React component without relying on dangerouslySetInnerHTML. I want to include other React components within the rendered HTML, but facing challenges when trying to render multiple elements or ...

Can you use ng-show within ng-if in Angular?

How can I make this input only show a property is true per the ng-if? The current code looks like this: <input type="button" class="naviaBtn naviaBlue" ng-if="ppt.Globals.hasDebitCard" ng-click="alertShow = (alertShow == 2 ? -1 : 2)" value="outstandin ...

The <form> element is giving me headaches in my JavaScript code

Trying to troubleshoot why my HTML pages render twice when I add a form with JavaScript. It seems like the page displays once with the script and again without it. Below is the basic HTML code: <form action="test.php" method="post"> <div class=" ...

Instructions for transferring a JavaScript array to a Java servlet

Greetings everyone! I am currently working on a web application with an orthodox approach, utilizing AJAX in Java and JavaScript. I am wondering if it is feasible to pass an array from JavaScript to a Servlet. ...

Matching only digits in Javascript using Regex when they are not immediately preceded or followed by letters

Looking to find digits but not when they are part of words (using JavaScript). The examples that should yield a match: 1 1,2 1.5-4 (matches 1.5 & 4 separately) (1+3) (matches 1 & 3 separately) =1; The following examples should NOT produce a matc ...

manipulating session variables with javascript ajax and php

I'm struggling with setting and retrieving session variables using JavaScript code that calls PHP functions via AJAX. I want to access the returned session field in my JavaScript, but nothing seems to be working. Can someone take a look at my code and ...

Achieve the identical outcome of the code in jQuery using React.js

Hey there! I'm currently exploring how to achieve similar results using React JS. I realize my request might seem a bit trivial, but I'm in the process of understanding how JavaScript and React JS can be connected in practical projects. Feel fr ...

Obtaining Beverage Overall with Loop

I am currently using a function to calculate the total of each drink, with a total of 5 drinks: var totalEstimate = 0; var locoCost = 0; var blackCost = 0; function calcLoco() { totalEstimate -= locoCost; locoCost = docume ...

An error is raised when attempting to refactor [].concat.apply([], [x]) to [].concat(x)

When attempting to refactor Array.prototype.concat.apply([], [x]) to [].concat(x), I encountered the following error message: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following ...

Searching DynamoDB in node.js using mapped items

In my DynamoDB table, I am trying to retrieve all Items where the Review.ID matches 123. Item: { id: 1, review: { Id: 123, step1: 456, step2: 789, step3: 1234, }, // Add more items here }, Item: { id: 2, review: { Id: 123 ...

Building a Multiple Choice Text Box with HTML

I am looking to create a section on my website where I can display text, and I have 9 buttons on the page that I want to stay within the same page without redirecting. The goal is for the text to update based on which button is clicked, with a fading ani ...

Selecting objects using a mouse pointer in Three.js

Is it possible to implement mouse picking on imported 3D models like a .obj file in Three.js? I've found plenty of tutorials for default objects, but I'm struggling to display a sphere at the exact position where the user clicks the model. Can an ...

What is the method to escape from a for loop in Protractor?

Check out my code snippet: formElements[0].findElements(by.repeater(repeater)).then(function(items){ console.log(i, '>>>>>>>>>.No of items in the list --- '+items.length); (function(items){ ...

Locating the source of the function call within a file in Node.js

Is it possible to determine the location of a file if a method from a module is called within that file? For example: // my-module.js module.exports = { method: function () { // I would like to know the path to my-app.js here } } // my-other-mod ...

What's the best method for uploading a file to AWS S3: POST or PUT requests?

Could you please provide insights on the advantages and disadvantages of utilizing POST versus PUT requests for uploading a file to Amazon Web Services S3? Although I have come across some relevant discussions on platforms like StackOverflow, such as this ...

Button to save and unsave in IONIC 2

I am looking to implement a save and unsaved icon feature in my list. The idea is that when I click on the icon, it saves the item and changes the icon accordingly. If I click on it again, it should unsave the item and revert the icon back to its original ...