将数组转换为排序对象
Transforming an array to a sorted object
我输入了一个数组数组,例如:
[
[ '1', '12:23', '16:27' ],
[ '1', '08:00', '17:59' ],
[ '2', '14:50', '15:14' ],
[ '2', '09:42', '11:00' ],
[ '3', '17:16', '17:41' ],
[ '3', '08:00', '17:59' ],
[ '4', '08:10', '13:01' ],
]
我希望能够使用数组的第一个元素作为键对象,将第二个和第三个元素存储在其中,并按第二个元素排序,如下所示:
{
1: [
['08:00', '17:59'],
['12:23', '16:27'],
],
2: [
['09:42', '11:00'],
['14:50', '15:14'],
]
3: [
['08:00', '17:59'],
['17:16', '17:41'],
]
4: [
['08:10', '13:01'],
]
}
提示?
将数组转换为对象是使用 Array.prototype.reduce() 的理想选择:
const arr = [
[ '1', '12:23', '16:27' ],
[ '1', '08:00', '17:59' ],
[ '2', '14:50', '15:14' ],
[ '2', '09:42', '11:00' ],
[ '3', '17:16', '17:41' ],
[ '3', '08:00', '17:59' ],
[ '4', '08:10', '13:01' ],
];
const obj = arr.reduce((acc, item) => {
const [key, timeA, timeB] = item;
// create array of time pairs if necessary
acc[key] = acc[key] || [];
// add time pairs to array
acc[key].push([timeA, timeB]);
return acc;
}, {});
// sort the time pair arrays by the first time
const compare = (a, b) => {
const aTime = a[0],
bTime = b[0];
return aTime.localeCompare(bTime);
};
Object.values(obj).forEach(arr => {
arr.sort(compare);
});
document.querySelector('pre').innerText = 'obj ' +
JSON.stringify(obj, null, 2);
<pre></pre>
我输入了一个数组数组,例如:
[
[ '1', '12:23', '16:27' ],
[ '1', '08:00', '17:59' ],
[ '2', '14:50', '15:14' ],
[ '2', '09:42', '11:00' ],
[ '3', '17:16', '17:41' ],
[ '3', '08:00', '17:59' ],
[ '4', '08:10', '13:01' ],
]
我希望能够使用数组的第一个元素作为键对象,将第二个和第三个元素存储在其中,并按第二个元素排序,如下所示:
{
1: [
['08:00', '17:59'],
['12:23', '16:27'],
],
2: [
['09:42', '11:00'],
['14:50', '15:14'],
]
3: [
['08:00', '17:59'],
['17:16', '17:41'],
]
4: [
['08:10', '13:01'],
]
}
提示?
将数组转换为对象是使用 Array.prototype.reduce() 的理想选择:
const arr = [
[ '1', '12:23', '16:27' ],
[ '1', '08:00', '17:59' ],
[ '2', '14:50', '15:14' ],
[ '2', '09:42', '11:00' ],
[ '3', '17:16', '17:41' ],
[ '3', '08:00', '17:59' ],
[ '4', '08:10', '13:01' ],
];
const obj = arr.reduce((acc, item) => {
const [key, timeA, timeB] = item;
// create array of time pairs if necessary
acc[key] = acc[key] || [];
// add time pairs to array
acc[key].push([timeA, timeB]);
return acc;
}, {});
// sort the time pair arrays by the first time
const compare = (a, b) => {
const aTime = a[0],
bTime = b[0];
return aTime.localeCompare(bTime);
};
Object.values(obj).forEach(arr => {
arr.sort(compare);
});
document.querySelector('pre').innerText = 'obj ' +
JSON.stringify(obj, null, 2);
<pre></pre>