How to append elements in an array to another array?

652 views Asked by At

How to append elements in an array to another array using Ramdajs with a single line statement?

state = {
   items:[10,11,]
 };

newItems = [1,2,3,4];

state = {
  ...state,
  taggable_friends: R.append(action.payload, state.taggable_friends)
}; 

//now state is [10,11,[1,2,3,4]], but I want [10,11,1,2,3,4]
2

There are 2 answers

0
Ori Drori On BEST ANSWER

Ramda's append works by "pushing" the 1st param into a clone of the 2nd param, which should be an array:

R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests']
R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']]

In your case:

R.append([1,2,3,4], [10,11]); // => [10,11,[1,2,3,4]]

Instead use RamdaJS's concat, and reverse the order of the parameters:

R.concat(state.taggable_friends, action.payload)
0
Henrik R On

If you want to use just basic JavaScript you can do this:

return {
  ...state,
  taggable_friends: [...state.taggable_friends, action.payload],
}