Exploring the power of using the splice function within a 2D array in

I've been working on this 2D array and I'm facing an issue where I need to remove rows that have 5 or more instances of the number "one". I attempted to use the splice method (a.splice(j,1)), but it's not producing the desired result. I suspect this is because the splice method alters the overall row quantity, which in turn impacts the for loops.

Could it be a matter of incorrect usage of the splice method, or perhaps there's a better alternative method I should consider?

Thank you!

a = Array(7).fill(0).map(x => Array(10).fill(0))

for (let i = 0; i < 5; i++) {
  a[1][i + 2] = 1;
  a[4][i + 2] = 1;
  a[5][i + 2] = 1;
}

console.log(a);


let count = 0;
for (let j = 0; j < 7; j++) {
  for (let i = 0; i < 10; i++) {
    if (a[j][i] == 1) {
      count = count + 1;
    }
  }
  if (count > 4) {
    console.log("Line" + j);
    // a.splice(j,1);
  }
  count = 0;
  // a.splice(j,1);
}

Answer №1

Your use of the splice method is correct, but there is an issue with how you are iterating through the array. Rather than moving forward using increments (j is incremented), you should move backward by decrementing j. This will prevent changing array indices from interfering with your loop.

Take a look at the example provided below:

let matrix = Array(7).fill(0).map(x => Array(10).fill(0));

for (let i=0; i<5; i++) {
  matrix[1][i+2] = 1;
  matrix[4][i+2] = 1;
  matrix[5][i+2] = 1;
}

console.log("Original matrix:");
console.log(matrix);

for (let j = matrix.length - 1; j > 0; j--) {
  let count = 0;
  
  for (let i = 0; i < matrix[j].length; i++) {
    if (matrix[j][i] === 1) {
      count += 1;
    }
  }
  
  if (count > 4) {
    matrix.splice(j, 1);
  }
}

console.log("Filtered matrix:");
console.log(matrix);

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

Error: Unexpected token : encountered in jQuery ajax call

When creating a web page that requests remote data (json), using jQuery.ajax works well within the same domain. However, if the request is made from a different domain (e.g. localhost), browsers block it and display: No 'Access-Control-Allow-Or ...

When using $http in AngularJS, an error may occur when it

I ran a test on my PHP code independently and obtained the following output: {"tabId":1,"tabName":"Main","uId":"1"}{"tabId":2,"tabName":"Photography","uId":"1"} However, my AngularJS application is unable to receive the callback and is throwing an error ...

Steps to ensure an npm script completes all tasks before ending, regardless of any task failures

My NPM script is set up to run multiple tasks like this: "multiple": "task1 && task2 && task3" Unfortunately, if task2 encounters an error, the script will stop and task3 won't get executed. I'm wondering if ...

Issue with reactivity not functioning as expected within VueJS loop without clear explanation

Struggling with implementing reactivity in vue.js within a loop? The loop renders fine, but firing an event updates the content without visibly rendering the data on the page. The latest version of vue.js is being used with bootstrap and jquery. Despite a ...

Obtain JSON information and insert it into an HTML element

I'm currently faced with an issue regarding JSON data (fetching and posting it). Below is the code I have used, but unfortunately it is not working and I am unsure why. Upon checking with Firebug, it indicates the response as: 200 OK sourceforge.net 1 ...

Preventing loss of context in jQuery ajax when mixing HTML/JS and opening a <script> tag

I've encountered a situation where I'm using ajax to communicate with the backend, which is responding with a mix of HTML and JavaScript code. To load this content into a div, I'm using the html() function like so: $("#mydiv").html(ajaxRespo ...

Is it possible to populate a div using jQuery Datatable?

Seeking help with jQuery datatable as a newbie. How can I populate divs instead of tables with the data from an ajax call? The structure should resemble a table: <div id="wrap"> <div class="drow"> <div class="dco ...

JQuery functions are functioning properly in Internet Explorer 10, but are encountering issues in Internet Explorer

My JavaScript function calls a jQuery function that works in IE10 but not in IE7. function test() { // Display message before calling jQuery function... alert("Before"); // Call the jQuery function... $("#boxscroll").getNiceScroll().resize(); // Display m ...

Transform Local Date to a Date Instance

Can someone guide me on how to convert a locale date to a date object in the correct way? Take a look at the following code snippet: > new Date() 2021-08-25T15:37:51.425Z // UTC Date > new Date().toLocaleString() '8/25/2021, 6:37:51 PM&apos ...

Determine in PHP whether the values of an array are the same as the values of another array in the corresponding positions

In the process of creating a quiz using PHP, I have encountered an issue. I am working with two arrays - one being the answer key array and the other being an array based on the user's answers. My aim is to compare these arrays and determine how many ...

Producing numerous results from a single input

How can I ensure that users input their address correctly, including street, number, entrance, floor, and apartment, into a single form field without missing any of the values? Additionally, how can I then extract each value (street, number, entrance, floo ...

Performing various tasks using a Single Change Event in JQuery/JavaScript

Looking for assistance with implementing this javascript to automatically populate various fields when a selection is made in a dropdown menu. <select class="form-control" name='brands_list'> <option value="0">Seleziona il produttore ...

Triggering a click event on a radio input type using jQuery

I am having trouble assigning an event to a radio button. Despite searching for solutions online, I haven't been able to find anything that works. The latest solution I attempted involved the following code: $(document).ready(function() { $("#mo ...

What is the best way to display HTML using Highlight.js in a Vue component?

I'm working on incorporating highlight JS into my Vue project, and I am looking to display a div on the edges of my code. I've experimented with the following: <pre v-highlightjs="viewerHTML"><div>Something here</div><code c ...

In which location can one find the compiled TypeScript files within an Angular 2 project?

As a newcomer to learning Angular 2, I've come across tutorials that mention all compiled files should go into the dist folder. These compiled files refer to typescript files transpiled into JavaScript. However, upon creating my project using Angular ...

Electron Builder reminder: Make sure to include the author's email in the application package.json file

Encountering an Issue During Generation of Build Using Electron Builder. ⨯ Please provide the author's 'email' in the application package.json I attempted to add the email field to the package.json file as well. ...

Executing the JavaScript function on a batch of 6 IDs at once (should return every 6 calls?)

I'm curious if there's a function available that can group called data into sets of 6. Here's the expanded version of the code var currentResults; function init() { getProducts(); } function getProducts() { $.ajax({ url:" ...

Utilize the fetch function within a Vuex action

After creating a store action to fetch an API, I encountered an error when trying to dispatch it from the component's created lifecycle hook. The error message displayed was 'Cannot read property 'dispatch' of undefined'. Despite r ...

Is there a quicker alternative to the 500ms delay caused by utilizing Display:none?

My div is packed with content, including a chart from amCharts and multiple sliders from noUiSlider. It also features various AngularJS functionalities. To hide the page quickly, I use $('#container').addClass('hidden'), where the rule ...

A variety of menu items are featured, each one uniquely colored

In the user interface I developed, users have the ability to specify the number of floors in their building. Each menu item in the system corresponds to a floor. While this setup is functional, I am looking to give each menu item a unique background color ...