Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out JSON array depending on content of each value [duplicate]

Lets say that using JSON.parse I've gotten 4 possible answers (like a multiple choice quiz) together in an array. Each value of that array has a "characteristic" (I don't know how else to call it). I want to look for a specific characteristic through each value of the array and filter out those values who do not meet the condition.

Example array:

0: {correct: false}
1: {correct: true}
2: {correct: false}
3: {correct: false}

The first value (1) of the array is the correct answer because its "characteristic" indicates it by saying it is "true". I would like to make the console to print out the number of the correct value.

Example: The correct answer is: 1

Thanks for any help

like image 547
TBG Avatar asked Jan 01 '23 01:01

TBG


2 Answers

You can use findIndex() which returns the index of the first element of array which matches the condition.

const arr = [
   {correct: false},
   {correct: true},
   {correct: false},
   {correct: false},
]

console.log(`the correct answer is` + arr.findIndex(x => x.correct))
like image 122
Maheer Ali Avatar answered Jan 03 '23 14:01

Maheer Ali


As Maheer Ali said, you can use Array#findIndex, but it will return one value - the first one to meet the condition. In your example, if you have many objects with the correct key equaling true, you will still get one of them.

So, if you want all objects meeting the requirements, there are many solutions.


Array#reduce

As suggested by Maheer Ali in comments, you can try with Array#reduce.

Shorter, and with a unique loop over the array:

const arr = [
     {correct: false},
     {correct: true},
     {correct: false},
     {correct: true},
  ],
  filtered = arr.reduce((acc, item, index) => ((item.correct) ? [...acc, index] : acc), []);

console.log(`the correct answers are ${filtered.join(', ')}`);

Array#map and Array#filter

Try Array#map (with Array#filter for removing false values):

const arr = [
     {correct: false},
     {correct: true},
     {correct: false},
     {correct: true},
  ],
  filtered = arr.map((item, index) => ((item.correct) ? index : false)).filter((item) => (item));

console.log(`the correct answers are ${filtered.join(', ')}`);

However, the array will be looped through two times (one time by Array#map, and an other time by Array#filter.


for...in statement

Eventually, you could do this by pushing the indexes in an empty array by iterating the original one with a for...in loop:

const arr = [
     {correct: false},
     {correct: true},
     {correct: false},
     {correct: true},
  ],
  filtered = [];
  
for (let index in arr) {
  if (arr[index].correct) {
    filtered.push(index);
  }
}

console.log(`the correct answers are ${filtered.join(', ')}`);

like image 44
Kévin Bibollet Avatar answered Jan 03 '23 13:01

Kévin Bibollet