I had a hypothetical question for you, so excuse the code. This question regards a past test that I took, and an answer that I couldn't figure out, so it's not "doing homework," just something to satisfy my own curiosity. Unfortunately, I did not save any of my code.
Let's suppose we have the following input:
const input = [
["add", "Hello"],
["add", ", how"],
["add", "is it"],
["add", "going today?"]
]
How would one go about getting the following output:
["Hello",
"Hello, how",
"Hello, how is it",
"Hello, how is it going today?"]
I utilized an output array (output), looped through input, and on each iteration I pushed input[0][1] to output, and to no surprise I built up an array that's just input[0][i]. Very rough example:
const output = [];
for (let i = 0; i < input.length; i++ {
output.push(input[0][i];
}
=> ["Hello", ", how", "is it", "going today?"]
I had a few thoughts about how to go, but unfortunately ran out of time. One thought was just to iterate through the 'output' array and try to += a string, and then loop over that string (while it's being built) pushing to a final array. The other way was some sort of string builder, which I couldn't figure out.
Apologies if this is simple, I'm still learning.
Uses Array.reduce, then slice the array based on current index of input, finally join the slices.
const input = [
["add", "Hello"],
["add", ", how"],
["add", "is it"],
["add", "going today?"]
]
console.log(
input.reduce((pre, cur, index, itself) => {
pre[index] = itself.slice(0, index + 1).map(item => item[1]).join(' ')
// pre[index] = itself.slice(0, index + 1).filter(item => item[0] === 'add').map(item => item[1]).join(' ') // if assuming only join the action (verb) is 'add'
return pre
}, [])
)
You can do a simple loop and push string at each iteration
const input = [
["add", "Hello"],
["add", ", how"],
["add", "is it"],
["add", "going today?"]
]
function addStr(arr){
let newArr = []
let str = ""
for(let i=0; i<arr.length; i++){
str = str + arr[i][1]
newArr.push(str)
}
return newArr
}
console.log(addStr(input))
Similar to the other answer using reduce, but a different implementation that I tend to prefer because it's a bit easier to debug IMO:
const input = [
["add", "Hello"],
["add", ", how"],
["add", "is it"],
["add", "going today?"]
]
input.map(([_first, second]) => second)
.reduce(
(agg, newStr) => ([
...agg,
(agg[agg.length - 1] + " " + newStr).trim()
]),
[""]
)
.slice(1)
This gets you pretty close, but only caveat is that there's an oddity where you don't have a space between Hello and ", how" which is a bit difficult to reconcile programatically.