Convert an array containing arrays of booleans to a single array of booleans (Array<Array<boolean>> to Array<boolean>)

There is an array that contains multiple arrays of booleans, all of the same length.

arrBefore = [arr1, arr2, ..., arrn];

The goal is to create a new array that consists of boolean values where each index is true if any of the corresponding indexes in the inner arrays are true. Otherwise, it should be false.

arrBefore = [[true, false, false], [false, false, false], [true, false, true], [true, false, true]];

arrAfter = reduceMyArr(arrBefore);

console.log(arrAfter);

//[true, false, true]

Instead of using for loops, the task is to achieve this using map() and reduce(). Seeking assistance as I couldn't find a suitable solution online.

update 1

To avoid confusion from previous answers, clarification is needed on comparing the inner array indexes. The resulting array should have the same length as the inner arrays, with each element being true if at least one true is found across the inner arrays at that specific index.

update 2

Additional examples provided upon request:

arrBefore = [[true],[false],[true],[false]];
arrAfter = [true];
---
arrBefore = [[true, false],[false, false], [false, true], [false, false], [true, true]];
arrAfter = [true, true];
---
arrBefore = [[true, false, false, false], [true, true, false, false]];
arrAfter = [true, true, false, false];
---
arrBefore = [[true, true, false, false, false], [false, false, false, false, true]];
arrAfter = [true, true, false, false, true];

Answer №1

If you're looking to simplify this task, consider using a Generator function. This approach involves providing an array with sub-arrays and then iterating through each sub-array to perform an OR operation on the items at the same index. Here's a brief outline of how this method would function:

start:

  iteration 1:
  mainArray = [ [a01, a02, ..., aNN], [b01, b02, ..., bNN], [c01, c02, ..., cNN] ]
                 ^^^                   ^^^                   ^^^
  pointer         |                     |                     |
  OR together:   a01        ||         b01         ||        c01                   --> result01

  iteration 2:
  mainArray = [ [a01, a02, ..., aNN], [b01, b02, ..., bNN], [c01, c02, ..., cNN] ]
                      ^^^                   ^^^                   ^^^
  pointer              |                     |                     |
  OR together:        a02        ||         b02         ||        c02              --> result02

  ...

  iteration NN:
  mainArray = [ [a01, a02, ..., aNN], [b01, b02, ..., bNN], [c01, c02, ..., cNN] ]
                                ^^^                   ^^^                   ^^^
  pointer                        |                     |                     |
  OR together:                  aNN        ||         bNN         ||        cNN    --> resultNN

end

To execute this algorithm and retrieve an array from each iteration, you can utilize Array.from. Thus, you will obtain

[result01, result02, ..., resultNN]
as output.

Below is an implementation example:

function* sequentialOR(mainArray) {
  const iterators = mainArray.map(subArray => subArray[Symbol.iterator]());
  
  let allResults = iterators.map(it => it.next());
  
  while(allResults[0].done === false) {
    yield allResults
      .map(({value}) => value)
      .some(Boolean);
      
    allResults = iterators.map(it => it.next());
  } 
}

const input1 = [[true],[false],[true],[false]];
test(input1);

const input2 = [[true, false],[false, false], [false, true], [false, false], [true, true]];
test(input2);

const input3 = [[true, false, false, false], [true, true, false, false]];
test(input3);

const input4 = [[true, true, false, false, false], [false, false, false, false, true]];
test(input4);

function test(input){
  const output = Array.from(sequentialOR(input));

  console.log(
  `Input: ${JSON.stringify(input)}
Output: ${JSON.stringify(output)}`
  );
}

I've opted for Array#some in this context due to its expressiveness in implementing the OR logic. While Array#reduce can achieve similar results, using some simplifies understanding the OR operation:

arrayOfBooleans.reduce((a, b) => a || b, false)

The initial value being false represents the neutral element for OR operations. The use of reduce might be slightly less apparent compared to .some, but both methods are valid for deriving boolean outcomes.

This methodology can be generalized further by allowing different operations on each set of results. By providing a callback function, other operations can be executed easily. For instance:

const sequentialAND = sequentialOperation(arr => arr.every(Boolean));
const sequentialAdd = sequentialOperation(arr => arr.reduce((a, b) => a + b, 0));
const sequentialMax = sequentialOperation(arr => arr.reduce((a, b) => Math.max(a, b), -Infinity));
//and more variations

Answer №2

If you're looking to condense an array of boolean values into a single boolean, the choice of binary operation matters. In this scenario, using the or operation is necessary:

arrayOfBools.reduce((res, cur) => res || cur, false)

This approach will still function correctly even if the input array, arrayOfBools, is empty (returning

false</code as the default value in such cases).</p>

<p>Now, what about reducing an array of arrays into a single flattened array? This entails "flattening" the higher-order array using the <code>reduce
method:

higherOrderArray.reduce((res, cur) => res.concat(cur), [])

This method accomplishes the task effectively.

You now have the capability to flatten your array of arrays of booleans into a single flat array of boolean values and then reduce them to a single boolean. Keep in mind that utilizing a traditional loop may be more efficient.

An alternative approach involves flattening the higher-order array by leveraging the map method. You could map the array of arrays of booleans to an array of booleans using the aforementioned or-driven reduce, followed by another application of reduce.

A functional implementation could look like this:

const mapReduce = <TSource, TTarget, TReduced>
(map: (x: TSource) => TTarget) =>
    (reduce: (res: TReduced, cur: TTarget) => TReduced) =>
        (zero: TReduced) =>
            (arr: TSource[]) : TReduced => {
return !arr || !arr.length ? zero : arr.map(map).reduce(reduce, zero)

Just a friendly reminder - it's advisable to exercise caution when implementing code like this in a production environment, unless your team is fully onboard with functional programming concepts. This example primarily serves as a learning tool.

Answer №3

const initialArr = [true, false, false],[false, false, false],[true, false, true],[true, false, true]]

let finalArr = []

initialArr.forEach((innerArr) => {
  finalArr.push(!!innerArr.find((element) => element === true))
})

console.log(finalArr)

// [true, false, true, true]

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 access the phone's dialer?

I'm attempting to open the phone dialer in my worklight 6.2 hybrid application by clicking on a button and/or an anchor tag. See the code I've been using below: Button: <button onClick='window.parent.location.href = "tel:+1xxxx"'&g ...

JQuery Challenge: Solving Dynamic Modal Issues

I'm in the process of creating a webpage that features multiple divs, each with its own unique image and title. Within each div, there's a button that, when clicked, should grab the specific image and title and display them in a modal. However, I ...

Having trouble providing JSDoc annotations for a generic identity function

My expectation was that the following code would work: // @ts-check /** * @template A * @callback Identity * @param {A} a * @returns A */ /** * @template A * @type {Identity<A>} */ const id = (a) => a /** * @type {number} */ export co ...

Encountering difficulties in storing array data into MongoDB collection

I am facing an issue with connecting to two different MongoDB instances using different URLs. One URL points to a remote connection string while the other one is for a local MongoDB instance. Initially, I establish a connection to MongoDB using MongoClient ...

Steps for converting a JSON response into a .json file.Steps to transform a

I am looking to create a .json file within my local project directory. My goal is to store the response from a fetch API call, which is an array of objects, into a .json file. Here is the code snippet I am working with: ts : getRecords(){ this.serv ...

ajax memory leakage

Encountering a gradual memory leak issue in Internet Explorer and Firefox while utilizing a mix of ASP.NET AJAX and jQuery. The situation mirrors the one portrayed on this post: Preventing AJAX memory leaks, but with jQuery and ASP.NET AJAX instead of prot ...

Using TypeScript to pass an array list as a parameter in the HTTP native GET method

Attempting to send an array list parameter. The codeList parameter contains an array like this: [ { "projCode": "11-1115", "cblTagNo": "571_GE001-RC1" }, { "projCode": "11-1115", "cblTagNo": "571_GE001-S" } ] Encountering the erro ...

Using Angular route resolve to handle the sessionStorage login status

I have successfully created a login system using Angular JS. Once the user logs in, a session storage variable is set and they are redirected to a dashboard page (which should only be accessible when logged in). $window.sessionStorage["isLoggedIn"] = true ...

Can express-handlebars tags be utilized within an HTML script tag when on the client side?

For a while now, I've been facing a challenge. I'm in the process of building an application with express-handlebars and so far everything is going smoothly. The data that needs to be displayed on the webpages looks good thanks to the Helper func ...

Leveraging the div element for redirecting to a PHP script

I have a div that I typically use as a button to redirect to another page. However, this time I want it to execute some PHP code before moving on to the next page. <div class="build_detail_option_ele_wrap" onclick="location.href="builders_checkout.php" ...

Exploring the integration of query parameters in Postman using mongoose

In my code, I have a driver.js file that holds a driver schema, and a driverController.js file with REST methods including GET, POST, DELETE, and PUT. What I want to achieve is to send a GET request to http://localhost:3000/drivers?available=true This re ...

React's connect method is causing issues with my test case

Attempting to create a test case for my jsx file... Took a sample test case from another jsx file... The other file does not have the connect method... But this new file contains the connect method... Believe this is causing issues with my test case... Any ...

When evaluating objects or arrays of objects to determine modifications

How can we detect changes in table data when users add input to cells? For example, if a user clicks on a cell and adds an input, the function should return TRUE to indicate that there are changes. If the user just clicks on the cell without making any ch ...

What is the process for integrating Android Java code with Node.js code?

I have some code that I am trying to integrate with Node.js for Firebase notifications on my Android application. I found a blog post outlining the implementation here: The Node.js code listens to changes in my Firebase Database and triggers notifications ...

Attempting to execute this function to verify the presence of matching email addresses within the database

function checkEmail(){ var email = $("#email").val(); var xmlhttp = new XMLHttpRequest(); var url = serverURL() + "/checkIfEmailExists.php"; url += "?email=" + email; xmlhttp.onreadystatechange=func ...

Discover automatically generated titles for dynamic hyperlinks

I am looking to generate dynamic links for a collection of documents with varying names, such as Test, Test2, and so on. I want the link text to display as "Document TestN," where N is the specific document number. Currently, I am able to create the links ...

How do I combine Dj3 rotation?

How do I incorporate rotation into this code snippet: <html> <head> <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c8acfb88fbe6fde6fb">[email protected]</a>" data-semver="3 ...

Using Excel VBA to transfer a 2D array to a different worksheet

When working in VBA, I discovered a function that generates a 2D array called res. My goal is to transfer the array data to a different worksheet instead of the current one where the function is running. Even though this seems straightforward, my lack of e ...

Setting 2D string arrays with char pointers

I am attempting to populate a 2D array of strings using the following approach: char *text_data[10][4]; //10 rows, 4 columns //Assigning values to all rows for (i = 0; i < 10; i++) { strcpy(text_data[i][0], "a"); strcpy(text_data[i][1], "xyz") ...

Directive in AngularJS fails to trigger upon form reset

I encountered an issue with a directive used within a form, specifically when clicking on a button with the type reset. The problem can be replicated on this stackblitz link. The directive I'm using is quite simple - it sets the input in an error stat ...