What is the most efficient way to calculate the sum of all the numbers lying between the endpoints

I am faced with a complex array

The array looks like this:

 let arr = [[2, "OR", 22, 22, "OR", 22, 20], [300, "OR", 22, 300, "OR", 22, 22, "OR", 1], [1212, 2, "OR", 1]]

My goal is to extract and sum up all the numbers between "OR"

For instance, the modified array should be as follows:

[[2,"OR",44, "OR", 42],[300, "OR", 322, "OR", 42, "OR", 1], [1214, "OR, 1]]

I have been pondering over this for several days now, but haven't found a solution yet.

Answer №1

To efficiently handle this scenario, you can utilize the .reduce() method to determine whether to combine the current value with the previous one based on the presence of "OR". Since the data consists of an array of arrays, you will need to apply this logic to each sub-array using .map():

let arr = [[2, "OR", 22, 22, "OR", 22, 20], [300, "OR", 22, 300, "OR", 22, 22, "OR", 1], [1212, 2, "OR", 1]];

let res = arr.map(sub =>
    sub.reduce((acc, val, i) => {
        if (!i || [val, sub[i-1]].includes("OR")) acc.push(val);
        else acc[acc.length-1] += val;
        return acc;
    }, [])
);

console.log(res);

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

An npm list is always full of modules

As I prepare to install a package using npm, I noticed that my folder for the new project already has numerous items listed when I run npm list. Is it normal for the folder not to be empty at this stage? Have I made an error somewhere? ...

Spinning a CSS object around an axis

Trying to add a unique touch to my image rotation with CSS. While familiar with rotating around x, y, and z axis, I want to achieve a diagonal rotation this time. Wondering if there's a way to tweak the y axis for a more slanted effect on my image? ...

Node.js is having trouble locating a module that has been installed

Upon transferring my node.js application to a different PC (where it functioned flawlessly on the development machine) and manually installing all the necessary dependencies, I encountered an error when attempting to run it: C:\Users\myself>n ...

issue with deploying a software package and getting it installed

I developed a basic package containing only a simple <div> x </div> and published it using npm publish. When I attempted to install it in a project using npm i, I encountered the following error message: Support for the experimental syntax &apo ...

Unloading a dynamically-loaded child component in Vue.js from the keep-alive cache

I have a question that is similar to the one mentioned here: Vue.js - Destroy a cached component from keep alive I am working on creating a Tab System using Vue router, and my code looks something like this: //My Tab component <template> <tab& ...

Storing persistent JSON data in a mobile app built with HTML5 involves utilizing the local storage capabilities of the

I am currently working on a mobile app using PhoneGap that is based on HTML technology. When the app is opened for the first time, my goal is to have it download a zip file that includes a JSON file and media files such as images or audio. Once the zip f ...

The mouseenter event in jQuery is failing to trigger

I'm encountering an issue with the mouseenter event on a div section of my webpage. I am attempting to alter the background color of this div when the mouse enters, but it seems to be disregarded. This is the basic HTML code: <div id="services" c ...

Can one open a unique custom pop-up before the window is about to close?

Seeking a way to create a pop-up confirmation dialog for users when they try to log out or stay on the page while logged in. I attempted using the code below, but haven't been able to find the correct solution: window.onbeforeunload = function (e) { ...

A simple guide on how to display a child object in a materialUI select dropdown from a parent object

I am developing a ReactJS application where I aim to showcase child objects from the parent object in a dropdown using materialUI select. Despite attempting to iterate over the object using the map() function, I haven't been able to retrieve values up ...

The inputs for Node express middleware are unclear and lack definition

I am currently exploring Node.js as a potential replacement for my existing DOT NET API. I have created middleware to enforce basic non-role authorization in my application, but I am encountering compilation problems with the function inputs. Compilation ...

Is it possible to utilize Mouse hover to distinguish between various elements in React?

In an attempt to enhance this code, I wanted to make it so that when you hover over a specific element, another related element would also be displayed. Using useState in React seemed to be the most effective way to accomplish this after trying out a diffe ...

Issue with generating PDF in AngularJS: pdfMakeTypeError occurs due to inability to read 'ownerDocument' property within html2canvas

Whenever I try to export by clicking the export button, this code is triggered: $scope.export = function() { html2canvas(document.getElementById('balanceSheet')).then(function(canvas) { document.body.appendChild(canvas); ...

Unusual behavior observed in AngularJs local variables

This code snippet is from the controller: cat1=[]; $.getJSON('categories/1/', function(data) { cat1 = data; //this returns a JSON object }); //cat2..4 are also JSONs $scope.pictures=[cat1,cat2,cat3,cat4,cat5]; The issue here seems to be th ...

Tips for blocking submissions when a user tries to input a hyperlink

I have encountered a problem in my journey of learning JS and unfortunately, I couldn't resolve it by myself. Lately, spam has been flooding through the form on my website and all my attempts with jQuery and JS to fix it have failed. As a last resort ...

Develop search bar button and file directory components

Within this application, there is a search engine designed to scan through the file tree for specific content. The goal is that upon entering a search query and clicking the Search button, the file tree will filter and display the relevant information. Cu ...

How can I fix the position of the close button when using the paper component of a modal in material ui to ensure responsiveness on the screen

I recently created a cards page where multiple cards are displayed. Each card opens a modal component when clicked, but unfortunately, the close button is not functioning properly. Here's an image showing the issue with the button's position whe ...

Messages and responses from an array within a discord.js bot

Currently, I am attempting to set up my discord.js version 12.0.0 bot to react to specific words using arrays for words and corresponding responses. However, I am encountering the following error message: TypeError: Cannot read property 'split' o ...

Guide for bringing in a complete npm library into React Native beyond just a single file access

Currently, I am facing an issue with importing the sjcl library into my project. Even though there are multiple files within the library, I am only able to import one file successfully. This is what I have tried from the command line: npm install sjcl -- ...

Steps to replace the content of an HTML file (such as modifying images) by clicking on an element in a separate HTML file

Currently, I am in the midst of a project and wondering if it is possible to dynamically modify the content of an HTML file, such as images and text, using JavaScript. My goal is to achieve this without relying on any frameworks, simply by clicking on el ...

Restricting Meteor Publish to specific user (admin) for all collections

Is there a method to exclusively publish all meteor collections to users with the role of {role: "admin"}? The meteor autopublish package grants database access to all clients. Are there any techniques to utilize the autopublish package while implementing ...