Thursday, May 20, 2021

Javascript Practice 57: JS Hero - Array: indexOf()

 
Question: 

Write a function concatUp that concatenate two arrays. The longer array should be appended to the shorter array. If both arrays are equally long, the second array should be appended to the first array.

Example: concatUp([1, 2], [3]) should return [3, 1, 2] and concatUp([5, 7], [6, 8]) should return [5, 7, 6, 8].





Answer: 

function concatUp (a1, a2) {

if (a2.length >= a1.length) {
return a1.concat(a2); 
} else {
return a2.concat(a1); 
}
};





> we declare a function concatUp 
> it has 2 parameters a1, a2
> this function will concatenate two arrays - a1 & a2
> the two arrays can be of equal length
> or a1 can be longer than a2
> or a2 can be longer than a1
> if a2 is longer than a1, then we append (meaning add to the end) a2 to a1
> like this: a1.concat(a2)
> if a1 length is equal to a2 length then we again append a2 to a1
> so we have 2 conditions for same output
> else if a1 is longer than a2 then we append a1 to a2
> like this: a2.concat(a1)

No comments:

Post a Comment