我為此使用javascript。我有一個資料集如下:
var filteredValues = [{
type1 : [ ],
type2 : [{w:86,h:108,l:66}, {w:86,h:109,l:66}],
type3 : [{w:82,h:110,l:73}]
}]
我希望能夠根據h用戶提供的值將此資料集過濾到最近的專案。示例:如果用戶提供105as h,則會發生以下情況
type1將被丟棄,因為目前沒有選擇任何內容。105h將與 和的值匹配,type2并且type3將選擇最接近的值。在這種情況下,{w:86,h:108,l:66}fromtype2as105最接近或等于109or110(fromtype3) 。- 輸出的結果將是型別名稱,在這種情況下
type2
如果您發現任何錯誤,請隨時糾正問題。此外,如果您認為更改資料集可以使其更容易,請告訴我。
以下是一些有趣的執行緒,可能會有所幫助
如何在嵌套陣列javascript中找到最近的元素?
在陣列中查找具有最接近值的物件
更新:
我嘗試了以下
function getResult(filteredValues, 105){
filteredValues.reduce((acc, obj) =>
Math.abs(y - obj.s) < Math.abs(y - acc.s) ? obj : acc
);
}
非常感謝您提前。
uj5u.com熱心網友回復:
我剛剛撰寫了這段代碼,它似乎可以作業,但它需要進行更多測驗(它更大但可能更容易理解):
const filteredValues = [
{
type1: [],
type2: [
{ w: 86, h: 108, l: 66 },
{ w: 86, h: 109, l: 66 },
],
type3: [{ w: 82, h: 106, l: 73 }],
},
];
function filter(h) {
const keys = Object.keys(filteredValues[0]);
const values = Object.values(filteredValues[0]);
const length = keys.length;
let tempType = keys[0];
let tempClosestHValue = values[0][0]?.h ?? Infinity;
for (let i = 0; i < length; i ) {
const type = values[i];
const key = keys[i];
if (type.length > 0) {
let closestHValue = Math.abs(type[0].h - h);
for (let y = 0; y < values[i].length; y ) {
let data = values[i][y];
if (Math.abs(data.h - h) < closestHValue) {
closestHValue = data.h;
}
}
if (closestHValue < tempClosestHValue) {
tempClosestHValue = closestHValue;
tempType = key;
}
}
}
return tempType;
}
console.log(filter(105));
它回傳“type3”,但如果h將第三種型別的屬性修改為 110,則會得到“type2”作為輸出。
uj5u.com熱心網友回復:
此解決方案僅采用給定資料的物件。
隨著條目,
- 過濾空陣列
- 通過采用絕對增量來映射減少陣列的結果,以獲得最小的可能值到目標值。
最后從條目創建一個新物件。
const
data = { type1: [], type2: [{ w: 86, h: 108, l: 66 }, { w: 86, h: 109, l: 66 }], type3: [{ w: 82, h: 110, l: 73 }] },
height = 105,
result = Object.fromEntries(Object
.entries(data)
.filter(([_, { length }]) => length)
.map(([k, v]) => [k, v.reduce((a, b) => Math.abs(a.h - height) <= Math.abs(b.h - height)
? a
: b
)])
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/425121.html
標籤:javascript 数组 目的 多维数组
