gpt4 book ai didi

javascript - 使用reduce 将数组转换为对象数组

转载 作者:行者123 更新时间:2023-12-03 02:00:04 24 4
gpt4 key购买 nike

optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore']

result = [
{start: bengaluru, end: salem},
{start: salem, end: erode},
{start: erode, end: tiruppur},
{start: tiruppur, end: coimbatore},
]

我想将optimizedRoute转换为结果。我想用 ES6 .reduce() 来做到这一点。这是我尝试过的:

const r = optimizedRoute.reduce((places, place, i) => {
const result: any = [];
places = []
places.push({
startPlace: place,
endPlace: place
});
// result.push ({ startplace, endplace, seats: 4 });
// console.log(result);
return places;
}, {});
console.log(r)

最佳答案

您可以使用reduce来获取路线的起点和终点部分,并返回下一次起点的终点。

getParts = a => (                   // take a as array and return an IIFE
r => ( // with an initialized result array
a.reduce((start, end) => ( // reduce array by taking two values
r.push({ start, end }), // push short hand properties
end // and take the last value as start value for next loop
)),
r // finally return result
)
)([]); // call IIFE with empty array

const getParts = a => (r => (a.reduce((start, end) => (r.push({ start, end }), end)), r))([]);

var optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore']

console.log(getParts(optimizedRoute));
.as-console-wrapper { max-height: 100% !important; top: 0; }

<小时/>

@EDIT Grégory NEUT 添加解释

// Two thing to know first :

// When no initial value is provided,
// Array.reduce takes the index 0 as first value and start to loop at index 1

// Doing (x, y, z)
// Will execute the code x, y and z

// Equivalent to :

// x;
// y;
// z;

let ex = 0;

console.log((ex = 2, ex = 5, ex = 3));

// So about the code

const getParts = (a) => {
// We are creating a new function here so we can have an array where to
// push data to
const func = (r) => {
// Because there is no initial value
//
// Start will be the value at index 0 of the array
// The loop is gonna start at index 1 of the array
a.reduce((start, end) => {
console.log(start, end);

r.push({
start,
end,
});

return end;
});

return r;
};

return func([]);
};

// Equivalent
const getPartsEquivalent = (a) => {
const r = [];

// Because there is no initial value
//
// Start will be the value at index 0 of the array
// The loop is gonna start at index 1 of the array
a.reduce((start, end) => {
console.log(start, end);

r.push({
start,
end,
});

return end;
});

return r;
};

var optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore']

console.log(getPartsEquivalent(optimizedRoute));
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}

关于javascript - 使用reduce 将数组转换为对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51396832/

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