gpt4 book ai didi

javascript - 如何在数组数组中的相同索引处获取最大值?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:12:11 25 4
gpt4 key购买 nike

我有这样的数据:

data = [
[{a: "b", value: 12}, {a: "bb", value: 39}, {a: "bb", value: 150}],
[{a: "c", value: 15}, {a: "cc", value: 83}, {a: "ccc", value: 12}],
[{a: "d", value: 55}, {a: "dd", value: 9}, {a: "dd", value: 1}]
]

我想在这个数据中获取相同索引处的最大值,所以我希望结果是这样的:

[55, 83, 150]

现在,我可以获取对象中的每个值,如果我指定索引,我可以获取最大值。我不确定如何处理每个索引。

let array = [];
data.map((eachArr, index) => {
array.push(eachArr[0].value)

for(let i = 0; i < eachArr.length; i++){
console.log('eachArr[i].value', eachArr[i].value, i);
}
})
console.log(Math.max(...array)) ===> 55

我该怎么做?

我认为人们误解了我的问题。我不想要每个数组中的最大值。我想要每个数组中具有相同索引的 value 的最大值。所以我想要 55 来自 12、15、55、83 来自 39、83、9 和 150 来自 150、12、1。很抱歉没有具体说明。我应该有一个不同长度的例子。

最佳答案

使用Array#reduce使用 Array#forEach 的方法方法。

var data = [[{ a: "b",value: 12}, { a: "bb",value: 39 }, { a: "bb", value: 150 }], [{   a: "c",   value: 15 }, {   a: "cc",   value: 83 }, {   a: "ccc",   value: 12 }], [{   a: "d",  value: 55 }, {   a: "dd",   value: 9 }, {   a: "dd",   value: 1 }]];


console.log(
// iterate over the array
data.reduce(function(arr, ele) {
// iterate over the inner array
ele.forEach(function(o, i) {
// check element present at the index, if not then update with current value
arr[i] = arr[i] || o.value;
// check assign greatest value by comparing with previous value
arr[i] = arr[i] < o.value ? o.value : arr[i];

// you can combine above two lines
// arr[i] = !arr[i] || arr[i] < o.value ? o.value : arr[i];

});
// return the array reference
return arr;
// set initial value as an empty array
}, [])
)


// without any comments
console.log(
data.reduce(function(arr, ele) {
ele.forEach(function(o, i) {
arr[i] = !arr[i] || arr[i] < o.value ? o.value : arr[i];
});
return arr;
}, [])
)


ES6 arrow function :

let data = [[{ a: "b",value: 12}, { a: "bb",value: 39 }, { a: "bb", value: 150 }], [{   a: "c",   value: 15 }, {   a: "cc",   value: 83 }, {   a: "ccc",   value: 12 }], [{   a: "d",  value: 55 }, {   a: "dd",   value: 9 }, {   a: "dd",   value: 1 }]];

console.log(
data.reduce((arr, ele) => (ele.forEach((o, i) => arr[i] = !arr[i] || arr[i] < o.value ? o.value : arr[i]), arr), [])
)


使用具有相同逻辑的简单 for 循环。

var data = [[{ a: "b",value: 12}, { a: "bb",value: 39 }, { a: "bb", value: 150 }], [{   a: "c",   value: 15 }, {   a: "cc",   value: 83 }, {   a: "ccc",   value: 12 }], [{   a: "d",  value: 55 }, {   a: "dd",   value: 9 }, {   a: "dd",   value: 1 }]];

var res = [];

for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].length; j++) {
res[j] = !res[j] || res[j] < data[i][j].value ? data[i][j].value : res[j];
}
}

console.log(res);


仅供引用: Performance comparison

关于javascript - 如何在数组数组中的相同索引处获取最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41843872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com