Tips for locating an entire row sequence within a 2D array?

What is the best way to count the number of rows in a matrix that do not contain a zero value?

The code snippet provided only counts the number of columns, but I require the number of rows:

var items = [
      [1, 0, 1],
      [3, 3, 3],
      [5, 6, 5]
    ];
    let result=[]
    function getNonZeroRows(list){
    for(let i = 0; i < list.length; i ++){
      for(let j = 0; j < list[i].length; j ++)
    {
      if(list[i][j] != 0)
        result.push(i);
    }
    return result;
    }

    }
    console.log(getNonZeroRows(items));

The expected result should be to have numbers [1, 2] representing the number of rows without zeros.

Answer №1

This code provides a straightforward solution:

const findNonZeroRows = items => items
  .map ( (_, i) => i )
  .filter ( i => ! items [i] .some (x => x == 0) )

var items = [ [1, 0, 1], [3, 3, 3], [5, 6, 5] ];

console .log (
  findNonZeroRows(items)
)

The map function converts the outer list into a list of indices.

Then filter is used along with some to check if any element in each row at that index has a value of 0.

If you prefer the actual rows instead of their indices, a simpler approach would be:

const findNonZeroRows = items => items .filter (row => ! row .some (x => x == 0))
.

Update

In response to a query:

Could you please simplify the syntax? :(

While the current version is already simple, we can improve it by using a dedicated range function like this:

const range = (lo, hi) => Array .from ( {length: hi - lo}, (_, i) => i )

This enables usage as follows:

const findNonZeroRows = (items) => 
  range (0, items.length)
  .filter ( i => ! items [i] .some (x => x == 0) )

This rearrangement doesn't simplify matters further but does enhance the structure. It's considered a better alternative.

We could also alter the function within filter. Instead of

  .filter ( i => ! items [i] .some (x => x == 0) )

we could modify it to:

  .filter ( i => items [i] .every (x => x != 0) )

Using the not-equal sign might enhance readability compared to standalone not, although both are equally simple.

Javascript limitations may prevent further simplification beyond this point. Perhaps what you're looking for is familiarity rather than simplicity. For more insight on complexity and simplicity, I recommend Rich Hickey's talk on Simple Made Easy.

I've demonstrated several steps that could make the code appear more familiar to certain individuals. However, these changes illustrate why prioritizing simplicity over easiness is crucial. Please refrain from implementing them.

Utilizing Function Expressions

An initial modification involves replacing arrow functions with traditional function expressions:

const findNonZeroRows = function (items) {
  return items.map (function (item, index) {
    return index;
  })
  .filter (function (index) {
    return ! items [index] .some (function(value) {
      return value == 0;
    })
  })
}

This version adds explicit function and return statements while changing single-expression bodies to curly braces. Although visually cluttered, no reduction in complexity occurs.

Let's proceed to worsen matters.

Note that the function's structure remains a series of one-liners such as

(input).map(someFunction).filter(anotherFunction)
, thereby lacking space for debugging statements or named intermediate variables.

Naming Intermediate Values

This updated version permits insertion of an essential console.log statement midway through processing:

const findNonZeroRows = function (items) {
  const indices = items .map (function (item, index) {
    return index;
  });
  // console.log(`Indices found`, indices);
  const nonZeroesIndices = indices .filter (function (index) {
    return ! items [index] .some (function(value) {
      return value == 0;
    });
  })
  return nonZeroesIndices;
}

Introducing variable assignments veers away from simplicity and introduces extra elements to the codebase.

Transitioning to a Single Loop

To address potential performance concerns, particularly iterating over rows twice, consider switching to plain for loops:

const findNonZeroRows = function (items) {
    const nonZeroesIndices = [];
    for (let rowIndex = 0; rowIndex < items.length; rowIndex++) {
        const row = items[rowIndex]
        let anyZeros = false
        for (let index = 0; index < row.length; index++) {
            if (row[index] === 0) {
                anyZeros = true;
                break;
            }
        }
        if (!anyZeros) {
            nonZeroesIndices.push(rowIndex)
        }
    }
    return nonZeroesIndices;
}

Conclusion

The sarcasm used is not directed towards anyone specifically but originates from experiences during my career. Embracing advanced coding techniques leads to enhanced skills and career progression. Remember to prioritize simplicity over easiness when writing code.


1 The digression regarding optimization was intended humorously. Avoid complicating your code unless profiling demonstrates specific sections causing severe performance bottlenecks.

Answer №2

Below is a code snippet that you can try out:

var items = [
    [1, 0, 1],
    [3, 3, 3],
    [5, 6, 5]
];

function h(list) {
    let result = []; // initializing the result variable inside the function
    for (let i = 0; i < list.length; i++) {
        for (let j = 0; j < list.length; j++) {
            if (list[i][j] !== 0)
                result.push(list[i][j]) // pushing values instead of keys
        }
        // return statement should be placed here to return resulting array
    }
    return result;
}

console.log(h(items));

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

What is the best way to incorporate a sidebar menu in an HTML webpage?

I am interested in creating a sidebar menu for my website using either HTML, CSS, or JavaScript. The W3 Schools website has a side menu that I find appealing and would like to create something similar. ...

The text sliding feature gradually moves further away from the left side with each iteration

I am in the process of transferring an existing slider from one website to another. Instead of creating a text slider from scratch, I decided to modify the code I found for the new site. However, the slider is not functioning correctly on the new site. Th ...

Can a JavaScript function spontaneously run without being called upon?

<a onclick="determineCountry(data)" class="installbtn">Install</a> My goal is to have the user redirected to one of three sites based on their location when they click the button above. However, there seems to be an issue with the script below ...

Choose a minimum of one validation for the list item

When I have a form in JSP that includes a drop-down view with multiple options, I want to ensure that at least one option is selected before the form can be submitted. If no options are selected, the form should not be able to submit. Thank you in advance ...

Arranging items by their total sum of arrays in React.js

I'm working with data.js where I have stored my JSON information. Here's a snippet: [ { name: 'Adam Doe', city: 'New York', mark: [8,10,10,10] }, { name: 'Catlyn Stronk', ...

Progress bar status displayed while uploading multiple files

I'm currently working on a Django project where I have set up a page to input data information about a file and then upload the file itself. https://i.sstatic.net/jB5cr.png Whenever the user clicks on the 'More datasets' button, it dyna ...

updating an element within an array without needing to stringify the array using JavaScript in Google Apps Script

Utilizing app script to retrieve data from an API and convert it into JSON format. var data = UrlFetchApp.fetch(***); var obj = JSON.parse(data); // Convert to JSON Logger.log(typeof(obj)); // Returns object type Here is an example of the returned JSON ar ...

Utilizing Observables in NestJS: Exploring SSE and EventEmitter

I am working on a project where I need to display an event that occurs in the backend on the frontend. Since it is a one-way communication, I have decided to use SSE (Server Sent Events) in nestjs to push the event to the frontend. The setup, as per the do ...

What are some strategies for containing elements within a parent div to prevent them from overflowing when new elements are dynamically added

Situation: I am currently working on a project that involves creating a dynamic input box where users can add words that are displayed individually in bubbles. To achieve this, I am attempting to have a div container placed side by side with an input field ...

Is it possible for the children of a Three.js scene to have matrix positions that differ from the children of those children?

I am facing an issue with my ferris wheel. The baskets on the wheel are not aligning correctly when the scene is rotated: https://i.sstatic.net/Ek1mT.png Everything functions as intended until the scene is rotated, causing the baskets to misalign with th ...

Activate an action only upon closing the page

I am looking for a solution in my vue.js app to execute a function only when the user closes the application. I have tried registering an event listener for beforeunload, but it causes the function to also trigger on page reloads, which is not ideal. Is t ...

Devising a method to display configurable products as related items along with their customizable options in Magento

I am in the process of creating an e-commerce website using Magento for a client. The issue I am facing is that when I include a configurable product as a related item, it displays the product but without a checkbox. From what I have researched, Magento do ...

Arranging an array based on numerical values embedded in strings

My array is as follows: var arr = [ '4msterdam', 'Par1s', 'N3w York', '2urich']; Is there a way to sort the elements of this array based on the numbers included in each string? ...

Using VueJS to dynamically manipulate URL parameters with v-model

Hello, I am new to coding. I am working on calling an API where I need to adjust parts of the querystring for different results. To explain briefly: <template> <div> <input type="text" v-model="param" /> ...

Locally hosted website failing to transfer login details to external domain

Having trouble with an ajax call that is supposed to retrieve data from a web page, but instead returns a jQuery parse Error. Even though I can access the page directly, the ajax call doesn't seem to be working and storing the result properly. Below ...

The controller element in AngularJS becomes undefined when invoked within a directive

Presented below is a snippet of my controller: myApp.controller('WizardController', function ($scope, $http) { $scope.user = { addressline1: null, cobuyer: null, validate: null, cobuyerfirstname: null, cobuyerlastname: null, ...

Automatically calculate line total using jQuery when input blurs

Within my interface, I have a section that allows users to input their class information for reimbursement. There are 6 line items available for them to fill out with the cost of books and tuition. Ideally, I would like the user to be able to enter these c ...

During the development of my project using the MERN Stack, I faced a challenge that needed to be

I recently ran into an issue while working on my MERN Stack project. The React app is running on port 3000 and the Express API on port 5000. The problem arose when I tried to add OAuth functionality using Redux, as I started getting an error message that ...

Component fails to trigger @click handler

.vue component <template> <div class="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> Loading Files </div> < ...

Modify the color of the components in Select from Material-UI

After reviewing numerous questions and answers on this topic, I have yet to find a suitable solution for my issue. Seeking guidance from the community for assistance. Utilizing the Select component from @mui/material to showcase the number of records per ...