繁体   English   中英

将数组减少为共享某些属性的对象:值

[英]Reduce Array to objects that share certain property: values

> 一切都在这里: https://jsfiddle.net/qr6hdbx0/

这是我的代码:

var viewport = {
    width: 'undefined',
    height: 'undefined',
    ratio: 1.7
};

var bg_1280x720 = {
    name: 'RZ_BG_1280x720_16-9.png',
    width: '1280',
    height: '720',
    ratio: 1.7
};

var bg_1920x1080 = {
    name: 'RZ_BG_1280x720_16-9.png',
    width: '1280',
    height: '720',
    ratio: 1.7
};

var bg_2000x2000 = {
    name: 'RZ_BG_2000x2000_1-1.png',
    width: '2000',
    height: '2000',
    ratio: 1
};

bgOverlays = [
bg_1280x720,
bg_1920x1080,
bg_2000x2000
]

我需要一个脚本,它查看: viewport.ratio ,然后查看.ratio: values bgOverlays所有对象的值,然后创建一个新数组,其中只有最接近的对象: viewport.ratio ,就它们而言: .ratio: value

此示例中的预期结果为:newArray [bg_1280x720, bg_1920x1080]

我不知道该怎么做,我发现教程显示如何将数组减少到只有一个值,即最接近给定值,但在我的情况下,数组中可能有两个 object 具有相同价值,但我没有让它工作...... - 我非常感谢任何形式的投入。 谢谢你! – 西蒙

逻辑是从每个 object 中创建一个视点的.ratio值之间的differences数组,从而从中找到最小的数字并将该值与对象数组中的值相匹配。希望我没有混淆任何人

 var viewport = { width: 'undefined', height: 'undefined', ratio: 1.6 }; var bg_1280x720 = { name: 'RZ_BG_1280x720_16-9.png', width: '1280', height: '720', ratio: 1.7 }; var bg_1920x1080 = { name: 'RZ_BG_1280x720_16-9.png', width: '1280', height: '720', ratio: 1.7 }; var bg_2000x2000 = { name: 'RZ_BG_2000x2000_1-1.png', width: '2000', height: '2000', ratio: 1 }; bgOverlays = [ bg_1280x720, bg_1920x1080, bg_2000x2000 ] // I need a script, that looks at: "viewport.ratio" and then looks at the ".ratio: values" of all the objects in: "bgOverlays" and then creates a new array that has only the objects in it, that are closest to: "viewport.ratio", in terms of their: ".ratio: value". // example: // viewport.ratio = 1.1 output: newArray[bg_2000x2000] // viewport.ratio = 2 output: newArray[bg_1280x720, bg_1920x1080] //well here you go:) var low=bgOverlays.map(a=>Math.abs(a.ratio-viewport.ratio)).sort((a,b)=>ab)[0] var newArray=bgOverlays.filter(a=>Math.abs(a.ratio-viewport.ratio)==low) console.log(newArray)

据我了解,您将 -0.1 到 0.1 视为接近比率值,我将使用一个变量,您可以根据您认为的“接近”值进行更改。

 var viewport = { width: 'undefined', height: 'undefined', ratio: 1.7 }; const gapThatIConsiderClose = 0.1 var bg_1280x720 = { name: 'RZ_BG_1280x720_16-9.png', width: '1280', height: '720', ratio: 1.7 }; var bg_1920x1080 = { name: 'RZ_BG_1280x720_16-9.png', width: '1280', height: '720', ratio: 1.7 }; var bg_2000x2000 = { name: 'RZ_BG_2000x2000_1-1.png', width: '2000', height: '2000', ratio: 1 }; function closerRatioObjects(){ return bgOverlays.filter(obj => obj.ratio <= viewport.ratio + gapThatIConsiderClose && obj.ratio >= viewport.ratio - gapThatIConsiderClose) } bgOverlays = [ bg_1280x720, bg_1920x1080, bg_2000x2000 ] console.log(closerRatioObjects())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM