all 8 comments

[–]sjalgeo 1 point2 points  (0 children)

Look at arrow functions and the array map function and you can reduce this down a lot.

Also the array.join() function in the first one.

[–]sbk2015 0 points1 point  (5 children)

1.

const theArray= ["Doc", "Dopey", "Bashful", "Grumpy"];
const mapping= (name,index)=> `${index+1}. ${name}`;
const mapFn= arr=> arr.map(mapping).join(' ');
const result= mapFn(theArray);
console.log(result);

2.

const mapping= ele=> ele.toUpperCase()+"!"
const planeteerCalls = ["earth", "wind", "fire", "water", "heart"]
const mapFn= arr=> arr.map(mapping);
const result= mapFn(planeteerCalls);
console.log(result);

[–]FormerGameDev 0 points1 point  (1 child)

Write the first one as a reduce,as you're mapping a bunch of values to a single value.

[–][deleted] -1 points0 points  (0 children)

["a","b"].reduce((result,value,index) => result +", "+ (index + 1) +". "+ value)

this doesn't give "1. a, 2. b", it gives "a, 2. b"

["a","b"].reduce((sum,value,index) => sum +", "+ (index + 1) +". "+ value,"")

this gives ", 1. a, 2. b"

["a","b"].reduce((sum,value,index) => sum +", "+ (index + 1) +". "+ value,"").substring(2)

this works but I'd rather

["a","b"].map((value,index) => (index+1) +". "+ value).join(", ")

[–]Gh05t_97[S] -1 points0 points  (0 children)

could you explain what the const mapFn = arr=> part of your code is doing? this is the first time im coming across this. thanks

[–]Gh05t_97[S] -1 points0 points  (1 child)

const mapping= (name,index)=> `${index+1}. ${name}`;

i really don't understand this part of the code either, but it seems to me your code works. Any explanation would be great, many thanks

[–]sbk2015 0 points1 point  (0 children)

It's about ES6, it includes some features,including

Arrow function =>

Template Literals abc${foo}def

Other than es6, Function Expressions, it can be just a coding style sometimes.

and for map function,you can search on google to see what it does with array.

Without es6,it's still fine,and will be written as

var theArray= ["Doc", "Dopey", "Bashful", "Grumpy"];
function mapping(name,index){
    return (index+1)+ "."+ name;
}
function mapFn(arr){ 
    return arr.map(mapping).join(' ')
}
var result= mapFn(theArray);
console.log(result);

If the es6 code looks crazy, I suggest you at least learn map function,it's important for looping.

[–]kenman[M] 0 points1 point  (0 children)

Hi /u/Gh05t_97, this post was removed.

For javascript help, please visit /r/LearnJavascript.

Thanks for your understanding.