Is there a way to retrieve the final elements from a deeply nested array?

I've been struggling to extract the last item from a nested array of objects. I've tried using methods like flatMap, flat, filter, and splice, but so far haven't had any luck getting the desired array.

const array = [
  [
    {
      total_cases: 18,
    },
    {
      total_cases: 32,
    },
    {
      total_cases: 7,
    },
  ],
  [
    {
      total_cases: 4,
    },
    {
      total_cases: 52,
    },
  ],
  [
    {
      total_cases: 68,
    },
  ],
];

The provided array structure is shown above. Can anyone suggest a way to extract only the last object's total_cases value into a new array?

The expected new array should look like this:

[7, 52, 68]

Your assistance is greatly appreciated!

Answer №1

Update according to the revised question.

To extract only the last element of each nested array and then retrieve the total_cases values, you can employ methods such as map, slice, and flat:

const array = [
  [ 
    { total_cases: 18 },
    { total_cases: 32 },
    { total_cases: 7 },
  ],
  [ 
    { total_cases: 4 },
    { total_cases: 52 },
  ],
  [ 
    { total_cases: 68 },
  ],
];

const result = array
  .map(a => a.slice(a.length - 1))
  .flat(1)
  .map(o => o.total_cases)
  
console.log(result)

Initial Response

You may flatten the array, filter it based on the date attribute, and then use map to get the total_cases values:

const array = [
  [
    {
      date: "2020-02-25",
      total_cases: 18,
    },
    {
      date: "2020-02-26",
      total_cases: 32,
    },
    {
      date: "last-object",
      total_cases: 7,
    },
  ],
  [
    {
      date: "2020-02-26",
      total_cases: 4,
    },
    {
      date: "last-object",
      total_cases: 52,
    },
  ],
  [
    {
      date: "last-object",
      total_cases: 68,
    },
  ],
];

const result = array
  .flat(1)
  .filter(o => o.date == 'last-object')
  .map(o => o.total_cases)
  
console.log(result)

Answer №2

To fetch the last element of an array, you can utilize the .at() method with a negative parameter. This method allows you to count back from the end of the array. For example, using .at(-1) will return the last element in the array.

const array=[[{total_cases:18},{total_cases:32},{total_cases:7}],[{total_cases:4},{total_cases:52}],[{total_cases:68}]];

const result = array.map(e => e.at(-1).total_cases);

console.log(...result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Javascript continuously swaps out text from distinct strings in a loop

I wrote a loop to split a string and search for certain text to replace it with another string. Here is an example of what I have done: function replaceStr(str, find, replace) { for (var i = 0; i < find.length; i++) { str = str.replace(new RegE ...

What other ways can websockets be utilized besides comet?

Websockets offer a more efficient solution for comet (reverse Ajax, often achieved through long-polling). However, are there other ways we can utilize websockets? For instance: - Can websockets be used to facilitate communication between different bro ...

The challenge of vertically aligning text in a dynamically generated div

Currently, I am in the process of developing a straightforward application that allows for the dynamic addition of students and teachers. I am dynamically adding divs with a click function. To these dynamically created divs, I have assigned the class "us ...

PHP generating JSON array containing multiple arrays (data retrieved from MySQL)

I've been struggling to find a solution for this issue... Here is my code, the part causing trouble is how to create one large array from each SQL row: (the commented-out line is where the error occurs). $result = mysqli_query($con, "SELECT * FROM ` ...

Passing data from a child component to a parent component in Vue 3: How

Struggling with Vue 3 app authentication through event-emission from child to parent. Below is a snippet of the code: Child <template> <form class="msform"> <input @click="goToLogin" type="button" name=&q ...

Monitoring the health and availability of AWS S3 buckets via API for checking their status

While working on a node.js application, I successfully implemented s3 file upload. However, there have been instances when the s3 bucket goes down for maintenance or other reasons. To address this issue and keep users informed, I wanted to incorporate an A ...

Utilizing Loopback Callbacks within a Looping Structure

While working in a for-loop, I encountered an issue where I needed to access the loop variable 'i' from within a callback function but it was not accessible due to closure restrictions. Despite attempting different methods such as using (i) or ca ...

Using JQuery, eliminate the transition effect from a child CSS class

I am facing an issue with transitioning an ID that has a child class. My goal is to transition the ID only, without affecting the class within it. Despite going through CSS and jQuery documentation, I have been unable to achieve this. The transitions are c ...

German-formatted jQuery datepicker

Need help in changing jQuery datepicker formatting from MM/DD/YYYY to German style as d MMMM yyyy. Tried implementing the following code but encountering issues. <script type="text/javascript"> $(function () { $('.datepicker&ap ...

Utilizing children as a prop within a Vue component

In React, I can create a FancyList component like this: const FancyList : React.SFC<{},{}> ({children}) => ( <ul> {...children} </ul> ); const FancyListItem : React.SFC<{text: string}, {}> ({children}) => < ...

What is the process for issuing https requests with SuperAgent?

In my React Native Android project, I am utilizing SuperAgent, which works similarly to Node.js. My goal is to make an API call using the https protocol. However, when I simply use the following code: Req = SuperAgent .get(‘https://url...') ...

What is the best method for implementing click functionality to elements that share a common class using only pure JavaScript

I am struggling to figure out how to select specific elements with the same classes using only pure JavaScript (no jQuery). For example: <div class="item"> <div class="divInside"></div> </div> <div class= ...

Safari Glitch in Bootstrap 4

For a simplified version, you can check it out here: https://jsfiddle.net/dkmsuhL3/ <html xmlns="http://www.w3.org/1999/xhtml"> <title>Testing Bootstrap Bug</title> <!-- Bootstrap V4 --> <link rel="stylesheet" href="https://m ...

Cleaning up webpage content by removing specific characters using Python's Selenium

Currently, I am using Selenium with Firefox in Python and facing a challenge while matching elements on a webpage based on keywords from a list. To ensure successful element lookup, I need to remove special characters like ® and ™ from the web page. Un ...

Trouble with the JavaScript split function

I am trying to split the data in a specific way. Given a string value like this var str = "[:en]tomato[:ml]തക്കാളി[:]"; I am aiming for the following output: tomato,തക്കാളി. I attempted to achieve this using the code sni ...

Is the CSS scale activated by mouseover or click?

My CSS code successfully scales images, but the issue is that it affects every image on the page. I am looking for a solution to apply this CSS only when the user hovers over or clicks on an image. The challenge is that images are added by non-technical w ...

Tips for populating a DOJO Select using JSON data that includes various parameters instead of just label and value

I am trying to populate a DOJO select element with JSON data where the item values for value are expressed by the code property. Here's an example of what I have: //require dojo Select var select = new Select({ name: "stateSelect", ...

When sending multiple JSON objects in an HTTP POST request to an ASP.NET MVC controller action, they may not be properly bound

I am passing two JSON objects to an ASP.NET MVC controller action, but both parameters are showing as null. Can anyone identify the error, possibly related to incorrect naming? /* Source Unit */ var sourceParent = sourceNode.getParent(); var sourceUnitPa ...

Trigger the fire event on .click() except when text is being selected

I am currently working on a chat box project and I want the input field within the message area to automatically get focused when the user clicks anywhere in the chat box. However, I don't want this functionality to interfere with text selection for c ...

Determine the minimum and maximum width of jQuery UI resizable during the "resizestart" event

As a newcomer to Javascript, I am facing challenges navigating my way around. Currently, I am attempting to create a jQuery plugin that will facilitate resizing elements using the jQuery UI resizable plugin. My goal is to implement logic that dynamically ...