Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

collections - Return multiple values from ES6 map() function

Say I have something like this:

let values = [1,2,3,4]; 

let newValues = values.map((v) => {
  return v *v ; 
}); 

console.log(newValues); //[1,4,9,16]

Pretty straight forward.

Now what if I want to return multiple values for each of my objects?

eg.

let values = [1,2,3,4]; 

let newValues = values.map((v) => {
  return [v *v, v*v*v, v+1] ; 
}); 

console.log(newValues); //This is what I want to get 
                        //[1, 1, 2, 4, 8, 3, 9, 27, 4, 16, 64, 5]

I can use a reduce function

let values = [1,2,3,4]; 

let newValues = values.map((v) => {
  return [v *v, v*v*v,v+1] ;
}).reduce((a, c) => {

  return a.concat(c); 
}); 

console.log(newValues); 

But is that the best way to do this?

question from:https://stackoverflow.com/questions/46986710/return-multiple-values-from-es6-map-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With using only one reduce() you can do this. you don't need map(). better approach is this:

const values = [1,2,3,4];
const newValues= values.reduce((acc, cur) => {
  return acc.concat([cur*cur , cur*cur*cur, cur+1]);
    // or acc.push([cur*cur , cur*cur*cur, cur+1]); return acc;
}, []);

console.log('newValues =', newValues)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...