Gover123
Gover123

Reputation: 69

How do I add the same element to an array multiple times?

I'm making shopping cart,and I am a little bit confused. There is a counter which counts number of current product. For example: the user can buy 5 book or more. So , I need to make a function which adds the element аs many times as the user will select it.

I made something like this:

[...state.shoppingCart, new Array(state.booksNumber).fill({...action.book})]

But of course it makes a new array in array... So how can I just add elements to an array without deleting old elements or creating a new array inside the array?

I need a functional way, no loops.

Upvotes: 0

Views: 1126

Answers (4)

andoni
andoni

Reputation: 38

You are missing the spread operator inside the returning array for the new Array you created.

Adding the spread operator allows you to merge/concat both array items.

For example:

const arrayOne = [1,2,3];
const arrayTwo = [4,5,6];
const mergedArrays = [...arrayOne, ...arrayTwo] //[1,2,3,4,5,6]

Also assuming action.book is an object you want to add multiple times inside of the new Array() you've created, there is no need to spread it as it will fill the array with each object.

This function might help out with what you are looking for:

const addMultipleItems = (action) => {
    const items = new Array(state.booksNumber).fill(action.book);
    return [...state.shoppingCart, ...items];
}

Upvotes: 0

Daniel Pantalena
Daniel Pantalena

Reputation: 429

const newArray = new Array(state.booksNumber).fill({...action.book})
[...state.shoppingCart, ...newArray]

Upvotes: 1

Heretic Monkey
Heretic Monkey

Reputation: 12115

Simply use the spread syntax again:

[...state.shoppingCart, ...new Array(state.booksNumber).fill({...action.book})]

That will spread the new array into the existing array.

Upvotes: 0

Vivek Singh
Vivek Singh

Reputation: 685

You can use the concat method

 const a = new Array([1,3,4]).concat([1,3,4])
 console.log(a)

This will add the elements into the array.

Or you can try with spread operator.

const arr=[1,2,3,4]
const a = new Array([1,3,4,.... arr]);
console.log(a)

Upvotes: 0

Related Questions