You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据特征过滤JSON数组并输出正确选项的索引

Find the Index of the Correct Answer in Your Array

Got it, let's break down how to solve this. You've got a parsed array of option objects, and you need to find the index of the one where correct: true — here are the most straightforward ways to do it.

Method 1: Use Array.findIndex() (Most Concise)

This built-in array method is made exactly for this scenario: it returns the index of the first element that matches your condition.

// Your parsed array from JSON
const options = [
  { correct: false },
  { correct: true },
  { correct: false },
  { correct: false }
];

// Find the index of the correct answer
const correctAnswerIndex = options.findIndex(option => option.correct === true);

// Output the result
console.log(`The correct answer is: ${correctAnswerIndex}`);

Notes:

  • If no element with correct: true exists, findIndex() returns -1. You can add a quick check for this edge case:
    if (correctAnswerIndex !== -1) {
      console.log(`The correct answer is: ${correctAnswerIndex}`);
    } else {
      console.log("No correct answer found in the array.");
    }
    

Method 2: Manual Loop with forEach()

If you prefer a more explicit approach, you can iterate through the array and track the index manually:

let correctAnswerIndex = -1;
const options = [
  { correct: false },
  { correct: true },
  { correct: false },
  { correct: false }
];

options.forEach((option, index) => {
  if (option.correct === true) {
    correctAnswerIndex = index;
  }
});

// Output the result
if (correctAnswerIndex !== -1) {
  console.log(`The correct answer is: ${correctAnswerIndex}`);
}

This works just fine, but findIndex() is more idiomatic and concise for this specific task.

内容的提问来源于stack exchange,提问作者TBG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:19:17