0

I have this list of json elements (it comes from a extern service), with a pair of group and a name:

const list_lookup = [
  { "rowData": ["aabb" , "gabriel"]}, 
  { "rowData": ["bbcc" , "jake"]}, 
  { "rowData": ["ccdd" , "john"]}, 
  { "rowData": ["aabb" , "chris"]}
 ]; 

I need to take the last appearance of the group that the user typed and store your correspondent username. Like in this case if the users input is "aabb"

I need to take the last array, who is the last time that the "aabb" group appears. I tried many ways but i just dont know how to do this.

ionut-t
  • 1,121
  • 1
  • 7
  • 14
  • Use `Array.filter` to remove the other elements, then use [this](https://stackoverflow.com/a/12099341/5734311) to grab the last element. (also JSON is a text format, your code shows an object literal) –  May 26 '20 at 22:39
  • That is an Array of Objects, not an Array of Arrays and, like Chris G says, is not JSON. If you do `JSON.stringify(list_lookup);` that will show you what the JSON string looks like. – Stephen P May 26 '20 at 23:10

1 Answers1

1

With a bit of array.find and object destructuring you can username

const list_lookup = [{
  "rowData": ["aabb", "gabriel"]
}, {
  "rowData": ["bbcc", "jake"]
}, {
  "rowData": ["ccdd", "john"]
}, {
  "rowData": ["aabb", "chris"]
}];

const {
  rowData: [pr, username]
} = list_lookup.reverse().find(({
  rowData
}) => rowData.includes("aabb"));

console.log(username);
Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50
  • thanks bro, but in this case i would need to take the "chris" as result, because i want to take the last appearance of the group "aabb", could you help? thanks a lot – Gabriel Poletti May 26 '20 at 23:12
  • Updated answer. `array.reverse()` is not the best idea though. Perhaps it would be better if every object contain property `timestamp` so you can sort array descending by it and then get the first item – Józef Podlecki May 26 '20 at 23:27
  • Thanks a lot man, it worked for me. And another doubt, i couldnt use something like that after the includes to get the last item too? rowData(-1).pop() – Gabriel Poletti May 26 '20 at 23:35