-2

I am trying to get last value(date ex:"1995-01-01") out of an array of array and array structure looks like bellow,

[
  [
    "1995-01-01",
    345.41
  ],
  [
    "1995-02-01",
    3545.05
  ],
]

I have tried bellow code but its currently failing ,

var last;
mainArr.map((val,idx)=>{
    return last = val[ val.length() -1].date;
})
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Divakar R
  • 773
  • 1
  • 8
  • 36

4 Answers4

0

I cannot comment since my reputation is quite low on this account.

Change

return last = val[ val.length() -1].date;

to

return last = val[ val.length -1].date;

since length is a property and not a function, you dont need the parameters.

no_modules
  • 117
  • 7
  • Im going to give my two cents on the matter here. First of all this has nothing to do with react JS - that tag should not be added to the question. Second, the title says you want the last item of your array, but then you say that you want the first. – no_modules Sep 29 '22 at 13:26
0

You can make use of reduce function & fill the value based on the date property(if the date property is less than the stored one then override it).

const arr = [["1995-01-01",345.41],["1995-02-01", 3545.05]];

const result = arr.reduce((a,[date, value])=>{
    a ??= {date,value};
    if(new Date(date) < new Date(a.date)) a =  {date, value};
    return a;
}, null);

console.log(result);
gorak
  • 5,233
  • 1
  • 7
  • 19
0

const arr = [
  ["1995-01-01", 345.41],
  ["1995-02-01", 3545.05, 123321],
];

<!-- begin snippet: js hide: false console: true babel: false -->
const item = data[data.length - 1];  /// last item of first array (arr)
const lastItem = lastItem[lastItem.length -1];  /// last item of last array 
-1

I would recommend using the .pop() method, which returns the last item in a given list. If your inner lists always have the date at the 0th index, you can simply grab that from the "popped" last element. Ex:

const list = [[ "1995-01-01", 345.41 ], ["1995-02-01", 3545.05 ]];
const lastDate = list.pop()[0]; // your last date string

This will remove the last item from the list variable, so alternatively if you need to use list for additional logic, you can simply grab it with

const list = [[ "1995-01-01", 345.41 ], ["1995-02-01", 3545.05 ]];
const lastDate = list[list.length - 1][0]; // your last date string
tuckermassad
  • 126
  • 4