-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddLength.js
More file actions
38 lines (30 loc) · 1.05 KB
/
AddLength.js
File metadata and controls
38 lines (30 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* Instructions:
What if we need the length of the words separated by a space to be added at
the end of that same word and have it returned as an array?
Example(Input --> Output)
"apple ban" --> ["apple 5", "ban 3"]
"you will win" -->["you 3", "will 4", "win 3"]
Your task is to write a function that takes a String and returns an
Array/list with the length of each word added to each element .
Note: String will have at least one element; words will always be separated by a space.
*/
//My answer
function addLength(str) {
let words = str.split(" ");
let placeholderArray = [];
console.log(words.length);
for (let i = 0; i < words.length; i++) {
const currentWord = words[i];
// console.log(currentWord)
const wordLength = currentWord.length;
// console.log(wordLength)
placeholderArray.push(`${currentWord} ${wordLength}`);
}
return placeholderArray;
// console.log(placeholderArray)
}
console.log(addLength("the apple"));
//Best practice:
function addLength(str) {
return str.split(" ").map((s) => `${s} ${s.length}`);
}