Retrieve the final element of the array by using the "pop

Here is an array that I am working with:

{
  "data": [
    {
      "lat": 31.135859,
      "lng": 46.823952,
      "hd": 319
    },
    {
      "lat": 31.050476,
      "lng": 46.907204,
      "hd": 320
    },
    {
      "lat": 30.999023,
      "lng": 46.957184,
      "hd": 320
    },
    {
      "lat": 30.955353,
      "lng": 46.999352,
      "hd": 320
    }
  ]
}

I attempted to extract the last item from the array using the pop() method, however, I encountered this error message:

this.heading.pop is not a function

heading: [] = [];
for (let datas of getdata['data']) {
  this.heading = datas.hd;
  console.log("heading"+this.heading.pop());
}

this.heading.pop();

Answer №1

You're not utilizing the for loop effectively. A simpler approach would be:

let obj = { "data": [ { "lat": 31.135859, "lng": 46.823952, "hd": 319 }, { "lat": 31.050476, "lng": 46.907204, "hd": 320 }, { "lat": 30.999023, "lng": 46.957184, "hd": 320 }, { "lat": 30.955353, "lng": 46.999352, "hd": 320 } ] }

console.log(obj.data.pop().hd);

Answer №2

const lastItem = dataArray[dataArray.length - 1].tv;

Answer №3

If you're looking for a solution, you might want to give this one a shot:

const coords = { "locations": [ { "latitude": 37.7749, "longitude": -122.4194 }, { "latitude": 34.0522, "longitude": -118.2437 }, { "latitude": 41.8781, "longitude": -87.6298 }, { "latitude": 40.7128, "longitude": -74.0060 } ] }

console.log(coords.locations.reduceRight(item => item).longitude) // -74.0060

Feel free to give it a try and see if it works for you!

Answer №4

It seems like your goal was to extract the "hd" headers and retrieve the last one from them. You can achieve this by following the code snippet below

var obj = {
    "data": [
        {
            "lat": 31.135859,
            "lng": 46.823952,
            "hd": 319
        },
        {
            "lat": 31.050476,
            "lng": 46.907204,
            "hd": 320
        },
        {
            "lat": 30.999023,
            "lng": 46.957184,
            "hd": 320
        },
        {
            "lat": 30.955353,
            "lng": 46.999352,
            "hd": 320
        }
    ]
}

var heading = []

function getLast() {
    for (let datas of obj.data) {
        heading.push(datas.hd);
    }
    return heading.pop();
}

console.log(getLast());

There are more efficient methods available for achieving the same task which have been provided in previous responses.

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

Display images from an Array in a Java GUI application

For a programming project, I am trying to display two dice images when a button is clicked. Can someone please assist me with this task? Here is the progress I have made so far: public class Main extends Application { Button roll; Stage ...

Analyzing past values within an array for the Insertion Sort procedure

Currently, I am implementing the insertion sort algorithm. This algorithm involves comparing array elements with previous elements in the array. To accomplish this, I have created nested loops: scanf("%d", &size); //accepts array size int array[size] ...

Dropdown menu not updating after second Ajax request

Recently, I've run into a problem that I could use some assistance with. I wrote a jQuery script to update an existing dropdown menu (disabling or enabling options based on returned results). It seems to be functioning correctly, but only on the init ...

Using TypeScript: Incorporating a map function in type declarations

My current situation involves the following types: type Value = boolean | number | string class Struct<T extends Value[] = Value[]> { constructor(fmt: string) { } pack(...args: T): Buffer { } } I am seeking guidance on how to replace &l ...

Setting the base href in Angular dynamically during runtime

My Angular 7 application is deployed across a cluster of servers, each running multiple instances: http://server1:8081/my-app http://server2:8081/my-app Additionally, the app can be accessed through a load balancer that directs requests to an available s ...

Conditional items display on React-Autocomplete input

Although I am new to React.js, my familiarity with JavaScript has enabled me to start working on building a form that autocompletes fields with user information stored in a JSON data file. Luckily, I came across the react-autocomplete library which allows ...

Is it possible to combine two enums in TypeScript to create a single object with key-value pairs?

Incorporating two enums named Key and Label, as well as an interface called IOption, the goal is to generate an array of objects known as IOptions. const enum Key { Flag = 'flag', Checkbox = 'checkbox', Star = 'star&apo ...

Different types that are not interchangeable within a function declaration

Can conditional types in TypeScript achieve the following scenario? type Type1 = { field: string, } type Type2 = { field: number, } // Ensuring that arg1 and arg2 are either both Type1 or both Type2 const func = (arg1: Type1 | Type2, arg2: Type1 | ...

What is the best way to ensure that my variables are properly differentiated in order to prevent Angular --prod --aot from causing empty values at runtime?

While testing my code locally in production, the functions I've written are returning the expected values when two parameters are passed in. However, after running ng build --prod --aot, the variable name within the functions changes from name to t. ...

Converting XML nodes into an array

I am looking to extract all attributes from the ROW element in the provided XML. <?xml version="1.0" encoding="windows-1251"?> <DATAPACKET Version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.seavus.com/AML/XML- ...

Generating a generalized array from arrays of specific types in Clojure

Currently, I am tackling an issue with JFreeChart in clojure and find myself seeking assistance. Within JFreeChart's DefaultXYDataset, there is a method called addSeries which is utilized to incorporate series into the chart. The data expected for th ...

Using JQuery's $.post function to send an array as a request

As a newcomer to using JQuery and .post, I have a question: In PHP, I can post an array of multiple form input values like this: <input type="text" name="array[]" /> Is it possible to do the same with JQuery post? If so, what is the syntax? Curre ...

Converting JSONObject into a Document

Hello, I am new to using MongoDB and I am trying to figure out how to convert a JSONObject to a Document and then store it in MongoDB. Here is the code snippet that I have so far - I receive a service API response in JSON format. CloseableHttpResponse res ...

Component in Next.js fetching data from an external API

I am attempting to generate cards dynamically with content fetched from an API. Unfortunately, I have been unsuccessful in finding a method that works during website rendering. My goal is to pass the "packages" as properties to the component within the div ...

Solve problems with limitations on ng2-dnd drop zones

I successfully integrated drag and drop capabilities into my Angular 4 application using the ng2-dnd library. Within my application, I have containers that can be sorted, as well as individual items within each container that can also be sorted. My goal i ...

What is the best way to eliminate any extra spaces from a string using typescript?

Currently in my Angular 5 project, I am encountering an issue with using the .trim() function in TypeScript on a string. Despite implementing it as shown below, no whitespace is being removed and also there are no error messages appearing: this.maintabinf ...

Building a hierarchical tree structure from a Python dictionary of parent-child relationships in a flat format

I have a list of dictionaries that represent a hierarchical structure: [{ "parent": "com.company.object.kind.type.subtype.family.Feline", "class": "com.company.object.kind.type.subtype.family.species.Cat" }, { "parent": "com.company.object.kin ...

Efficient method to generate a sorted array from a pre-sorted array of elements in C++

Is there an alternative method to create a sorted array of member variables from a sorted array of custom objects in C++? For example, consider the following: class People{ public: //Could potentially contain multiple parameters. What are the possible ...

A data type labeled as 'undefined' needs to include a method called '[Symbol.iterator]()' which will then return an iterator

I've been working on converting my reducer from JavaScript to TypeScript, but I keep encountering a strange error that I can't seem to resolve. The issue arises when I attempt to use ellipsis for array deconstruction in the reducer [...state.mess ...

process.nextTick: Unable to access undefined properties (reading 'indexOf')

After initiating npm start in my Angular project, an error is triggered: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80e4e5ecadf0f2efeac0b0aeb0aeb0">[email protected]</a> build > ng build Node.js vers ...