0

I have an array of and array of objects similar to this :

const oldArray =[
[{'val': 12, 'rank':1},{'val': 122, 'rank':1},{'val': 112, 'rank':1}],
[{'val': 12, 'rank':2},{'val': 122, 'rank':2},{'val': 112, 'rank':2}],
[{'val': 12, 'rank':3},{'val': 122, 'rank':3},{'val': 112, 'rank':3}]
]

how can I retrieve the array that has the 'rank' values set to 3?

const newArray = [{'val': 12, 'rank':3},{'val': 122, 'rank':3},{'val': 112, 'rank':3}];

thanks in advance!

JK2018
  • 429
  • 1
  • 9
  • 23

2 Answers2

2

You could use Array.prototype.flat() with Array.prototype.filter() method to get the result.

const oldArray = [
  [
    { val: 12, rank: 1 },
    { val: 122, rank: 1 },
    { val: 112, rank: 1 },
  ],
  [
    { val: 12, rank: 2 },
    { val: 122, rank: 2 },
    { val: 112, rank: 2 },
  ],
  [
    { val: 12, rank: 3 },
    { val: 122, rank: 3 },
    { val: 112, rank: 3 },
  ],
];
const ret = oldArray.flat().filter((x) => x.rank === 3);
console.log(ret);
mr hr
  • 3,162
  • 2
  • 9
  • 19
0

Assuming all ranks within the inner arrays are the same you could use find() and check the rank of the first element within each array.

const oldArray = [
  [{'val': 12, 'rank':1},{'val': 122, 'rank':1},{'val': 112, 'rank':1}],
  [{'val': 12, 'rank':2},{'val': 122, 'rank':2},{'val': 112, 'rank':2}],
  [{'val': 12, 'rank':3},{'val': 122, 'rank':3},{'val': 112, 'rank':3}],
];

const newArray = oldArray.find(([element]) => element.rank == 3);
console.log(newArray);

This answer uses destructuring to extract the first element of each inner array.

This answer will also throw an error if the inner array can be empty (accessing "rank" of undefined), which can be avoided by using optional chaining. eg. element?.rank == 3

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52