stepheniok
stepheniok

Reputation: 405

JavaScript - Removing last index of an array

I am currently using a third party API to graph data on Highcharts.

This API returns data depending on the month we are in. For example, it returns data about March, April, May etc...

graphArrOne returns an array length of 251

graphArrTwo returns an array length of 250. graphArrayTwo only returns data up until April while graphArrayOne returns data up until May.

I am creating a condition to compare both lengths and if so slice the last index of the greater array.

My issue is how can I remove the last index of an array without specifying which index to slice? For example, if the API is updated an graphArrOne data now shows June, while graphArrayTwo shows May. I will like to still slice the last month.

Is there a way to remove the last index of an array without specifying which index?

My expected outcome is if graphArrOne is larger then graphArrTwo remove the last index from graphArrOne

My code:

if (graphArrOne.length > graphArrTwo) { 
    graphArrOne.slice(250,251) // this is what I'm trying to do.
}

Upvotes: 0

Views: 60

Answers (2)

Rajneesh
Rajneesh

Reputation: 5308

You can make use of pop()

if (graphArrOne.length > graphArrTwo.length) { 
    graphArrOne.pop()
}

The pop() method removes the last element from an array and returns that element.

Upvotes: 2

MonteCristo
MonteCristo

Reputation: 1550

You can use pop to remove last item of array.

let arr1 = [1, 2, 3];
let arr2 = [1, 2, 3, 4, 5];

if(arr1.length > arr2.length) {
  arr1.pop()
}

if(arr2.length > arr1.length) {
  arr2.pop()
}

console.log(arr1);

console.log(arr2)

Upvotes: 0

Related Questions