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(', ')}`);