I would like to merge multiple arrays that are already sorted, into one sorted array.
My arrays look like this :
{
"arrays": [
[
{
"type": "tag",
"position": "start",
"text": true,
"offset": 1280,
}
{
"type": "tag",
"position": "end",
"text": true,
"offset": 1350,
}
],
[
{
"type": "tag",
"position": "start",
"text": false,
"offset": 1121,
},
{
"type": "tag",
"position": "end",
"text": true,
"offset": 1300,
}
],
],
...
}
My current implementation looks like this :
function getMinFromArrays(arrays, state) {
let minIndex = -1;
for (let i = 0, l = arrays.length; i < l; i++) {
if (state[i] >= arrays[i].length) {
continue;
}
if (minIndex === -1) {
minIndex = i;
}
if (arrays[i][state[i]].offset < arrays[minIndex][state[minIndex]].offset) {
minIndex = i;
}
}
if (minIndex === -1) {
throw new Error("minIndex negative");
}
return minIndex;
}
module.exports = function (arrays) {
const totalLength = arrays.reduce(function (sum, array) {
return sum + array.length;
}, 0);
const resultArray = new Array(totalLength);
const state = arrays.map(function () { return 0; });
let i = 0;
while(i <= totalLength - 1) {
const arrayIndex = getMinFromArrays(arrays, state);
resultArray[i] = arrays[arrayIndex][state[arrayIndex]];
state[arrayIndex]++;
i++;
}
return resultArray;
};
I think It might be possible to optimize this code (sometimes, it seems to be quite slow (70ms for 10 arrays of size 5000 each).
offset
is the only property on which one would meaningfully sort. \$\endgroup\$