gpt4 book ai didi

javascript - 将数组拆分为从负到正的范围

转载 作者:数据小太阳 更新时间:2023-10-29 03:53:21 26 4
gpt4 key购买 nike

目前我有一个数组 levels 包含其他名为 level 的数组,这些数组包含 stages

我想用一个名为 position 的新属性映射关卡中的所有对象。该位置返回距数组中心的距离。我所说的中心是指 length/2

如果数组长度是偶数我想要以下范围

... -3.5 , -2.5 , -1.5 , -0.5 , 0.5 , 1.5 , 2.5 , 3.5 ...

如果数组长度不是偶数我想要以下范围

... -4 , -3 , -2 , -1 , 0 , 1 , 2 , 3 , 4 ...

我开始创造这个

const distanceLevels = [
[{
"id": 1
}, {
"id": 8
}],
[{
"id": 2
}],
[{
"id": 3
}, {
"id": 4
}, {
"id": 5
}, {
"id": 7
}],
[{
"id": 6
}]
];

function getViewLevels() {
const viewLevels = []; // the new array as the result

distanceLevels.forEach(level => { // one level containing the stages
const levelLength = level.length;
const halfLevelLength = levelLength * 0.5;
const levelLengthIsEven = levelLength % 2 == 0;

let viewLevel = []; // the mapped level

if (levelLengthIsEven) {
addViewStage(viewLevel, level[Math.floor(halfLevelLength)], 0);
}

for (let i = 0; i < halfLevelLength; i++) {
let rightPosition = i - halfLevelLength;
let leftPosition = i;
let leftStageIndex = i;

if (levelLengthIsEven) {
leftPosition++;
leftStageIndex += Math.floor(halfLevelLength) + 1;
} else {
rightPosition += 0.5;
leftPosition += 0.5;
leftStageIndex += halfLevelLength;
}

addViewStage(viewLevel, level[i], rightPosition);
addViewStage(viewLevel, level[leftStageIndex], leftPosition);
}

viewLevel = viewLevel.sort((a, b) => a.position > b.position); // sort the result by their position, means from negative to positive
viewLevels.push(viewLevel); // add this new view level
});

console.log(viewLevels); // <---- result here!
}

function addViewStage(viewLevel, stage, position) { // push a new element to the array
viewLevel.push({
stage: stage,
position: position
});
}

getViewLevels();

这是我得到的结果

result

我的数学真的很吃力。我想要做的就是将每个对象映射到 level from

阶段(对象)

{
stage: stage,
position: position // with the correct range
}

最佳答案

您可以使用两个嵌套的 map 来做到这一点:

const distanceLevels = [
[{
"id": 1
}, {
"id": 8
}],
[{
"id": 2
}],
[{
"id": 3
}, {
"id": 4
}, {
"id": 5
}, {
"id": 7
}],
[{
"id": 6
}]
]

const mappedLevels = distanceLevels.map(level =>
level.map((stage, index, lvl) => (
{...stage, position: index - (lvl.length - 1) / 2}
))
);

console.log(mappedLevels);

关于javascript - 将数组拆分为从负到正的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51149673/

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