0

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!

0

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry. I edited the question. We shouldn't use the date items.
@ffcabbar please see my edit. I've added code which doesn't rely on the date items.
2

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

1 Comment

This is best if you can guarantee a modern browser

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.