Navigating through Javascript Arrays with Conditions to Separate Objects

If we consider a variable called data, can we extract specific items from an array based on the totalaccount value? For instance, before the first occurrence of totalaccount, there are three accounts that I want to retrieve.

Similarly, before the final totalaccount excluding the initial one, there are two accounts for which I need information extraction. How can we transform the array into the desired format below?

let firstOne = {loanname: "Mr X", acnumber: "020000000000001", outstanding: "54000"},
    {loanname: "Mrs Y", acnumber: "020000000000087", outstanding: "87000"},
    {loanname: "Mr Z", acnumber: "020000000000103", outstanding: "15000"},

let secondOne ={loanname: "David", acnumber: "020000000000091", outstanding: "11000"},
    {loanname: "James", acnumber: "020000000001291", outstanding: "4000"}, 

Answer №1

To accomplish this task, utilize the reduce function.

Start by checking for the presence of the totalaccount property. If it exists, create a new array within the accumulator (acc) using the push method of Array.prototype. If the totalaccount property does not exist, simply push the object into the last array of acc. Keep track of the index of the last array element with current

const data = [
  { loanname: "Mr X", acnumber: "020000000000001", outstanding: "54000" },
  { loanname: "Mrs Y", acnumber: "020000000000087", outstanding: "87000" },
  { loanname: "Mr Z", acnumber: "020000000000103", outstanding: "15000" },
  { totalaccount: "3", outstanding: "156000" },
  { loanname: "David", acnumber: "020000000000091", outstanding: "11000" },
  { loanname: "James", acnumber: "020000000001291", outstanding: "4000" },
  { totalaccount: "2", outstanding: "15000" },
];

let current = 0;
const result = data.reduce((acc, curr) => {
    const { totalaccount } = curr;
    if (totalaccount) {
      acc.push([]);
      ++current;
    } else {
      acc[current].push(curr);
    }
    return acc;
  },
  [[]]
);

const [first, second] = result;
console.log(first);
console.log(second);
console.log(result);

You can achieve the same outcome without explicitly tracking the current index as shown below:

const data = [
  { loanname: "Mr X", acnumber: "020000000000001", outstanding: "54000" },
  { loanname: "Mrs Y", acnumber: "020000000000087", outstanding: "87000" },
  { loanname: "Mr Z", acnumber: "020000000000103", outstanding: "15000" },
  { totalaccount: "3", outstanding: "156000" },
  { loanname: "David", acnumber: "020000000000091", outstanding: "11000" },
  { loanname: "James", acnumber: "020000000001291", outstanding: "4000" },
  { totalaccount: "2", outstanding: "15000" },
];

const result = data.reduce(
  (acc, curr) => {
    const { totalaccount } = curr;
    if (totalaccount) {
      acc.push([]);
    } else {
      acc[acc.length - 1].push(curr);
    }
    return acc;
  },
  [[]]
);

console.log(result);

If you wish to aggregate into a single object and dynamically create properties

const data = [
  { loanname: "Mr X", acnumber: "020000000000001", outstanding: "54000" },
  { loanname: "Mrs Y", acnumber: "020000000000087", outstanding: "87000" },
  { loanname: "Mr Z", acnumber: "020000000000103", outstanding: "15000" },
  { totalaccount: "3", outstanding: "156000" },
  { loanname: "David", acnumber: "020000000000091", outstanding: "11000" },
  { loanname: "James", acnumber: "020000000001291", outstanding: "4000" },
  { totalaccount: "2", outstanding: "15000" },
];

const result = data.reduce(
  (acc, curr) => {
    const { totalaccount } = curr;
    if (totalaccount) {
      acc.push([]);
    } else {
      acc[acc.length - 1].push(curr);
    }
    return acc;
  },
  [[]]
);

const resultObj = {};
result.forEach((d, i) => {
  if (d.length) {
    resultObj[`collection${i + 1}`] = [...d];
  }
});
console.log(resultObj);

Answer №2

Check out this potential solution (not fully tested yet, just a concept)

const myArray = [];
for (let index = 0; index < info.length; index++) {
  if (!info[index].currentBalance) continue;
    myArray.push([]);
    for (let y = index - info[index].currentBalance; y <= index - 1; y++) {
      myArray[myArray.length-1].push(info[y]);
    }
}
console.log(myArray);

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

"Customizing the MsAdalAngular6Module setup on the fly - a step-by-step

In order to manage authentication in an Angular single page app, I am utilizing the microsoft adal wrapper available at https://github.com/manishrasrani/ms-adal-angular6. Following the documentation, I configure all necessary options during compile time u ...

How to toggle the visibility of a div with multiple checkboxes using the iCheck plugin for jQuery

I customized my checkboxes using the icheck plugin to work with both single and multiple checkboxes, including a "Check all" option. Here is an example of how it looks in HTML: HTML : <div>Using Check all function</div> <div id="action" c ...

Find a specific number within an array using Javascript, and if it is not found, return the closest

In Javascript, I want to find a number in an array. If the number does not exist in the array, I need to return a number that is lower than the target number. ...

How can I create a real-time page update using node.js?

I am completely new to node.js, but my main goal in learning this language is to achieve a specific task. I want to create a webpage where the content within a designated "div" can be swapped dynamically for users currently viewing the page. For example, ...

Can an element be targeted for hover in CSS without it being a child element?

In my HTML code, I have an <aside> and a <header>. The <header> contains a child element called container, which has some children including one named burger bar. What I am trying to achieve is that when I hover over the burger bar elemen ...

Dealing with an unexpected token error in JSON? Learn how to properly handle removing special characters like quotation marks and line breaks to

After receiving a JSON response from the server during page load, I successfully populate it on the page using Handlebars.js. However, I am facing difficulties in storing this JSON object in a JavaScript object. Here is what I tried: var jsObject = "{{o ...

What is the best way to access a variable within an event handler function?

Is there a way to retrieve values from the for-loop within an event handler? Consider this JSON array var items = [ { "id": "#id1", "name": "text1" }, { "id": "#id2", "name": "text2" } ]; that is passed as a parameter to the function function setHand ...

Translating PHP code into JavaScript

In my CodeIgniter setup, I have a PHP MySQL statement within a model: function getAllDevices() { $query = $this->db->query("SELECT * FROM Device_tbl ORDER BY Manufacturer"); return $query->result(); } After retrieving the data in the con ...

Restart following the execution of a Jquery function

I've implemented a jQuery function to expand one div when another is clicked: <script type="text/javascript"> $(document).ready(function() { $(".flip").click(function() { $(".module").slideToggle("slow"); }); ...

Divide the controller functionality from the factory operations in Angular

I'm looking to break up my code into smaller controllers instead of having everything in one large controller. However, I've come across this error: Argument 'protocolController' is not a function, got undefined I've created a fa ...

What is the best way to retrieve data from this array?

Some of the code I have extracted from serialized data appears to not be in an array format. When attempting to use a foreach loop, it results in an error. array ( 'last_submit' => '1', 'feeds_changed' => '1', ...

Angular problem arises when attempting to map an array and selectively push objects into another array based on a specific condition

Setting up a cashier screen and needing an addToCart function seems pretty simple, right? However, I am encountering a strange logical error. When I click on an item to add it to the cart, my function checks if the item already exists in the array. If it d ...

Executing .Net function in IronPython [Visual Studio 2012]

I want to utilize a .Net function in IronPython(VS-2012) .NET Function: public int GetData(uint numberOfSamples, float[] iBuffer, float[] qBuffer){..} IronPython: # This is my code in IronPython numSamples = 1024 from array import array iData = array(& ...

Guide to using normalize.css via npm installation with webpack

Currently, I am utilizing webpack in conjunction with ReactJS and am exploring the implementation of normalize.css after installing it via npm (). Does the normalize.css take effect immediately upon npm installation? If I were to make modifications to it, ...

Repeating promises resolutions yields stagnant outcomes

Within my Angular project, I am working with two distinct components. parent.component.ts mypromise = this.httpClient.get<any>('http://localhost').toPromise() parent.component.html <app-children #child [promise]="mypromise"></a ...

Is there a way to create an input field that accepts only numbers and behaves like a password field simultaneously?

I am attempting to develop an input field for entering a PIN. I would like the PIN to be masked on mobile devices, similar to how passwords are obscured in password input fields. I came across a suggestion on stackoverflow regarding this, but unfortunately ...

After deploying a NextJs app on Github Pages, only the readme file is displayed

After creating a basic e-commerce web app using next js (with nextjs 14), I attempted to deploy it with github pages. Despite following a tutorial on YouTube and trying the gh-page branch and GitHub actions methods, all that would show up when visiting the ...

What is the best approach to simultaneously update an array using multiple threads in a Node.js environment?

Hey there, I'm trying to figure out how to make changes to the same array using 2 worker threads in Node.js. Can anyone help me with this? My issue is that when I add a value in worker thread 1 and then try to access it in worker thread 2, the second ...

Encountering a TypeError stating that searchField.toLowerCase is not a function while employing hooks and redux in the

I've been working on a project to dive deeper into react. Recently, I made the switch to using hooks and attempted to integrate redux into it. However, I encountered an error that says: TypeError: searchField.toLowerCase is not a function After consu ...

Is it possible to validate a mongoose array by comparing it with another array to check for common strings

Exploring Mongoose Schema and Validation var interestSchema = new Schema({ active_elements: { type: [String] }, pending_elements: { type:[String] } }); interestSchema.methods.matchElements = function matchElements() { this.find({act ...