0

I got these 2 arrays and I would like to have a function (randomize() in this case) to be applied to each of them by calling the function and outputing the result to the console. Currently the console.log returns undefined

const array1 = ['I want to','You want to'];
let newArray1 = array1
            .map(item => ({value: Math.random(), item:item}))
            .sort((a,b)=> a.value-b.value)
            .map(item => item.item)
            .slice(0,1);



const array2 = [' eat',' sleep '];
let newArray2 = array2
                .map(item => ({value: Math.random(), item:item}))
                .sort((a,b)=> a.value-b.value)
                .map(item => item.item)
                .slice(0,1);


randomize = (x) =>{
  x.map(item => ({value: Math.random(), item:item}))
  .sort((a,b)=> a.value-b.value)
  .map(item => item.item)
  .slice(0,1);

}
randomize(array2);


console.log(randomize(array2));
KT-mongo
  • 2,044
  • 4
  • 18
  • 28

3 Answers3

4

You are missing the return statement in your randomize function

randomize = (x) =>{
  return x.map(item => ({value: Math.random(), item:item}))
  .sort((a,b)=> a.value-b.value)
  .map(item => item.item)
  .slice(0,1);  
}
Moti Korets
  • 3,738
  • 2
  • 26
  • 35
2

randomize is an arrow function with no return value. Either add a return statement or remove the curly braces to use the implicit return for arrow function's whose body only includes an expression.

const randomize = (x) => {
  return x.map(item => ({value: Math.random(), item:item}))
  .sort((a,b)=> a.value-b.value)
  .map(item => item.item)
  .slice(0,1);
}

or:

const randomize = (x) => 
  x.map(item => ({value: Math.random(), item:item}))
  .sort((a,b)=> a.value-b.value)
  .map(item => item.item)
  .slice(0,1)
;

Also, in case randomize hasn't been declared anywhere, I added the const keyword to avoid creating an implicit global.

Paul
  • 139,544
  • 27
  • 275
  • 264
-1

you are missing return in map function

const array2 = [' eat',' sleep '];

randomize = (x) =>{
  x.map(item => { return {value: Math.random(), item:item}})
  .sort((a,b)=> a.value-b.value)
  .map(item =>return  item.item)
  .slice(0,1);

}

randomize(array2);
Arash
  • 3,458
  • 7
  • 32
  • 50
  • adding unnecessary returns in the map functions will not make the containing function return a value. the other provided solutions are correct. – derelict Mar 28 '18 at 19:39