搜索最大值和具体值对应的键



我试图找到'序列'的最高键值,它的值是'真'。我知道这不是sql,但我想知道是否有可能在javascript上做这个请求。

例如,在我的例子中,我想要:5,因为"70"如果bug_tab为true,则该值为最大值。

这里我的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);

提前谢谢,

使用array。

另外,正如另一个用户所指出的,基于你的描述的正确答案是4,而不是像你说的5。

var arr = [{
"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"
}
];
var res = arr.reduce((acc, curr, idx, arr) => 
curr.bug_tab && +curr.sequence > +arr[acc].sequence ? idx : acc 
, 0);
console.log(res);

可以这样做,也许这不是最有效的方法但效果如预期

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

最新更新