I'm looping over the following array of arrays and for the first item in the array, I need to insert an object after every item, except the first and maybe last item. The data looks like this...
const data = [
['Path', 'Item1', 'Item2', 'Item3', 'Item4', 'Item5', 'Score'],
['/path-one', 1, 3, 2, 2, 4, 3],
['/path-two', 4, 5, 5, 5, 6, 3],
['/path-three', 5, 5, 3, 5, 3, 3],
['/path-four', 2, 3, 4, 2, 2, 3],
]
For the first row, except the first item and last item, after every other item I want to insert an object {role: 'annotation'}. For the rest of the rows, for every index in the first item array that has the role object, I want to duplicate the previous value such that if the first array after modification is:
['Path', 'Item1', {role: 'annotation'}, 'Item2', {role: 'annotation'}, 'Score'], then the other arrays will follow the pattern ['/path-one', 'value1', 'value1', 'value2', 'value2', 'value3']
My solution so far has been inadequate. Here's what I came up with...
let indexes = []
let scoreIndex
const result = data.map((item, index) => {
let clone = [...item]
item.map((i, ix) => {
if (index === 0) {
if (ix !== 0 && typeof clone[ix + 1] === 'string' && typeof clone[ix] !== 'object') {
if (clone[ix + 1] === 'Score') {
scoreIndex = ix
}
indexes.push(ix)
clone.splice((ix + 1), 0, {role: 'annotation'})
}
return i
} else {
if (indexes.includes(ix) && ix !== scoreIndex) {
item.splice((ix + 1), 0, i)
return i
}
return i
}
})
return clone
})
Your help would be greatly appreciated.