首页 > 解决方案 > 搜索最高值和特定值的键

问题描述

我试图找到'sequence'的最高键值,它的值为'true'。我知道这不是 sql,但我想知道是否可以在 javascript 上执行此请求。

例如,在我的情况下,我想要: 5 因为“70”它是最高值,而 bug_tab 为真。

这是我的 js 数组 myTab :

[
  {
    "value": "AHAH",
    "field": "15",
    "color": "",
    "bug_tab": true,
    "sequence": "40",
    "text": "slash"
  },
  {
    "value": "BABA",
    "field": "8",
    "color": "",
    "bug_tab": true,
    "sequence": "50",
    "text": "zip"
  },
  {
    "value": "CACA",
    "field": "25",
    "color": "",
    "bug_tab": false,
    "sequence": "63",
    "text": "vite"
  },
  {
    "value": "DADA",
    "field": "22",
    "color": "",
    "bug_tab": true,
    "sequence": "66",
    "text": "meat"
  },
  {
    "value": "EVA",
    "field": "13",
    "color": "",
    "bug_tab": true,
    "sequence": "70",
    "text": "zut"
  },
  {
    "value": "FAFA",
    "field": "jut",
    "color": "",
    "bug_tab": false,
    "sequence": "90",
    "text": "cut"
  }
]

我有什么:

这将返回 bug_tab 等于 true 的第一次出现:

var indexbugTabArray = myTab.map(function(o) { return o.bug_tab; }).indexOf(true);

提前谢谢,

标签: javascriptarrays

解决方案


可以这样做,也许这不是最有效的方式,但它可以按预期工作

const toto = [
  {
    "value": "AHAH",
    "field": "15",
    "color": "",
    "bug_tab": true,
    "sequence": "40",
    "text": "slash"
  },
  {
    "value": "BABA",
    "field": "8",
    "color": "",
    "bug_tab": true,
    "sequence": "50",
    "text": "zip"
  },
  {
    "value": "CACA",
    "field": "25",
    "color": "",
    "bug_tab": false,
    "sequence": "63",
    "text": "vite"
  },
  {
    "value": "DADA",
    "field": "22",
    "color": "",
    "bug_tab": true,
    "sequence": "66",
    "text": "meat"
  },
  {
    "value": "EVA",
    "field": "13",
    "color": "",
    "bug_tab": true,
    "sequence": "70",
    "text": "zut"
  },
  {
    "value": "FAFA",
    "field": "jut",
    "color": "",
    "bug_tab": false,
    "sequence": "90",
    "text": "cut"
  }
];

const max = {
  index: -1, // -1 so you can check if you find one
  value: 0,
};

toto.forEach((el, index) => {
  if (+el.sequence > max.value && el.bug_tab) {
    max.index = index;
    max.value = +el.sequence;
  }
});

console.log(max.index, max.value, toto[max.index]);


推荐阅读