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!

1
  • Use filter(). Commented Nov 19, 2020 at 1:26

2 Answers 2

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

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

Comments

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

Comments

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.