The partitionOn function takes 2 arguments, pred is a function that specifies the conditions for selecting elements from the items array.

The function must return the length of the new array with elements satisfying pred . And also change the array of items , which takes as an argument.

In my code, items does not change in the outer scope. How to make it change?

I am writing in the console

 window.items.concat(arrPredFalse, arrPredTrue); 

and it works, but codewars gives an error.

 function partitionOn(pred, items) { var arrPredTrue = []; var arrPredFalse = []; for (var i = 0; i < items.length; i++) { if (pred(items[i])) { arrPredTrue.push(items[i]); } else { arrPredFalse.push(items[i]); } } items.concat(arrPredFalse, arrPredTrue); return arrPredTrue.length; } 
  • use instead of concat , which returns a new array, splice which changes the array to which it is applied - Grundy
  • Thanks, helped - Vitalik Mileshko

1 answer 1

Concat line function

 items.concat(arrPredFalse, arrPredTrue); 

Creates a new array and returns it to nowhere. At the same time, there are no changes in the source array.

Assigning the result to the same items variable will also not affect the global array, because in this case, the link to which the items parameter will simply change.

For the changes to be applied, you must use the functions directly changing the array: push , splice

 items.push(...arrPredFalse, ...arrPredTrue); 

or

 items.splice(items.length, 0, ...arrPredFalse, ...arrPredTrue); 

The examples above use the spread operator , which simplifies the transfer of an array as a parameter list. Without using it, use apply

 items.push.apply(items, arrPredFalse.concat(arrPredTrue)); 

or

 items.splice.apply(items, [items.length, 0].concat(arrPredFalse,arrPredTrue));