ffcabbar
ffcabbar

Reputation: 371

How can I get the last items from a nested array?

I was struggling to get the last object item from a nested array. I tried to implement flatMap, flat, filter, and splice. However, I can not still get the expected array.

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

I have an array like the above. How can I get only the last-object item into a new array?

Expected new array should be like this:

[7, 52, 68]

Thanks in advance!

Upvotes: 0

Views: 1727

Answers (2)

Nick
Nick

Reputation: 147216

Edit based on changes to question.

You can use map and slice to select only the last element of each nested array, then flat to flatten the array and map again to select the total_cases values:

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)

Original Answer

You can flatten the array, filter it based on the date value and then use map to extract 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)

Upvotes: 3

A1exandr Belan
A1exandr Belan

Reputation: 4780

You can use .at() method. Negative parametr count back from the last item in the array. So .at(-1) return the last array's element.

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; }

Upvotes: 2

Related Questions