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)
答案 0 :(得分:14)
您可以使用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égoryNEUT 添加说明
// 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;
}
答案 1 :(得分:11)
另一种方法是结合使用map
方法和slice
。对于map
函数,您必须传递一个callback
函数作为 argument ,该函数将应用于给定 array 中的每个项目。
optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore']
var result = optimizedRoute
.slice(0, -1)
.map((item, index) => ({start : item, end : optimizedRoute[index + 1]}));
console.log(result);
答案 2 :(得分:11)
我不太了解“ with reduce”的要求,因为使用循环的相应代码可以立即读取并且不需要解释:
const optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore'];
const result = new Array(optimizedRoute.length - 1);
for (let i = 0; i < result.length; ++i) {
result[i] = {
start: optimizedRoute[i],
end: optimizedRoute[i + 1]
};
}
console.log(result)
有时候做些聪明的事情很有趣,但是相比之下,某些答案却非常复杂!
答案 3 :(得分:4)
这里是reduce
的示例。我不确定这是否是最自然的方法!
使用reduce
感觉很过分,在这种情况下(但这只是我的看法),我自然会使用索引,所以,我会进行一个简单的for
循环
const optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore'];
let startCity;
const result = optimizedRoute.reduce((acc, city) => {
if(startCity) {
acc.push({start: startCity, end: city});
}
startCity = city;
return acc;
}, []);
console.log(result);
答案 4 :(得分:3)
自从您要求reduce
以来,这是一种解决方法:
let optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore']
let res = optimizedRoute.reduce((accum, item, i)=>{
if(i == optimizedRoute.length - 1)
return accum;
accum.push({start: item, end: optimizedRoute[i+1]})
return accum;
}, [])
console.log(res);
答案 5 :(得分:3)
reduce
不太适合这里使用,因为您没有尝试将数组缩小为单个值。
在理想世界中,我们可以使用multi-array map
version,通常称为zip
const result = zipWith(optimisedRoute.slice(0, -1),
optimisedRoute.slice(1),
(start, end) => ({start, end}));
,但是JavaScript中没有。最好的替代方法是使用Array.from
在路由的一系列索引中map
:
const result = Array.from({length: optimisedRoute.length - 1}, (_, index) => {
const start = optimisedRoute[index];
const end = optimisedRoute[index + 1];
return {start, end};
});
答案 6 :(得分:2)
以下代码正在使用Spread operator
,Ternary operator
和Array.reduce
。
const optimizedRoute = [
'Bengaluru',
'Salem',
'Erode',
'Tiruppur',
'Coimbatore',
];
// Look if we are at dealing with the last value or not
// If we do only return the constructed array
// If we don't, add a new value into the constructed array.
// tmp is the array we are constructing
// x the actual loop item
// xi the index of the item
const lastItemIndex = optimizedRoute.length - 1;
const ret = optimizedRoute.reduce((tmp, x, xi) => xi !== lastItemIndex ? [
...tmp,
{
start: x,
// We access to the next item using the position of
// the current item (xi)
end: optimizedRoute[xi + 1],
},
] : tmp, []);
console.log(ret);
答案 7 :(得分:2)
我简化了妮娜·斯科尔斯的答案, 按照尼娜的想法,请使用reduce来获取路线的起点和终点,并为下一次起点返回终点。
getParts = a => {
const result = [];
a.reduce((start, end) => {
result.push({ start, end });
return end;
});
return result;
};
var optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore'];
console.log(this.getParts(optimizedRoute));
答案 8 :(得分:0)
我更喜欢可读性,而不是仅仅解决它们的短代码
optimizedRoute.reduce((routes, city, index) => {
const firstCity = index === 0;
const lastCity = index === optimizedRoute.length - 1;
if (!firstCity) {
routes.last().end = city;
}
if (!lastCity) {
routes.push({ start: city });
}
return routes;
}, []);
此外,该解决方案虽然缩短了,但却降低了可读性(至少对我而言),可能是:
optimizedRoute.reduce((routes, city) => {
routes.last().start = city;
routes.push({ end: city });
return routes;
}, [{}]).slice(1, -1);
关于last()
,这是我通常用于提高可读性的功能:
Array.prototype.last = function() {
return this[this.length - 1]
}
答案 9 :(得分:-1)
如果有人正在寻找,可以使用ReduceRight解决方案。
optimizedRoute.reduceRight((acc, d, i, arr) =>
i == 0
? acc
: [{ start: arr[i -1], end: d }, ...acc]
, [])