Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node - Access last index of multidimensional arrays

I have a question that I believe is straightforward, but I've seen conflicting answers on.

Let's say I have the following data structure:

const data = [
  ...,
  {
    someKey: [
      ...,
      {
        someDeepKey: [
          ...,
          'two'
        ],
      }
    ]
  }
]

So accessing the first index of all of the following would look like this:

data[0].someKey[0].someDeepKey[0]

But if I wanted to find the LAST index of all of these, I haven't found a clean method. I have seen some people recommend extending the Array prototype itself, which I feel is a bad idea.

The only other "clean" solution I can think of is to chain down variables to make it semi readable.

let someKey = data[data.length - 1].someKey
let someDeepKey = someKey[someKey.length - 1].someDeepKey
let someDeepKeyValue = someDeepKey[someDeepKey.length - 1]

Can anybody suggest a cleaner way to do this? I believe Python supports something neat such as:

data[-1].someKey[-1].someDeepKey[-1]

and I was wondering if there is anything similar in JS.

like image 637
Nicholas Hazel Avatar asked Nov 24 '25 21:11

Nicholas Hazel


1 Answers

Here small util using reduce, will be handy and works for any level of nesting.

const data = [
  {
    someKey: [
      {
        someDeepKey: ["one"],
      },
    ],
  },
  {
    someKey: [
      {
        someDeepKey: ["one", "two"],
      },
    ],
  },
];

const lastDeep = ["someKey", "someDeepKey", ""].reduce(
  (last, cur) => ((res = last[last.length - 1]), res[cur] ?? res),
  data
);

console.log(lastDeep);
like image 99
Siva K V Avatar answered Nov 26 '25 11:11

Siva K V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!