Insert random elements into a Java Script array

Asked

Viewed 75 times

2

Suppose I have the following array:

const arr = [1, 2, 4, 5, 7]

If I want to add the number 3 at position 02 of the array I would do as follows:

const add = arr.splice(2,0, 3)
console.log(arr)

The question is: What is the best way to add also number 6 at position 4 of the array in this same const add

  • 1

    The "number 6 at position 4" is not really a "random element", as commented in the title. What I meant by "random elements"?

  • 1

    It is worth remembering that splice returns an array with the deleted elements. But as you pass zero in the second parameter, no element is deleted, so add will always be an empty array (that is, in this code snippet this variable seems unnecessary - unless, of course, the code is in a larger context in which the return is relevant, then it makes sense to store it in a variable)

2 answers

1

Thus:

 arr.splice(2, 0, 3, 4)

You can also do so:

const array = [3, 4]

arr.splice(2, 0, ...array)
  • Lucas the problem is that the new items are inserted into different indexes. If the problem was to insert n items in a specific index your solution would be perfect.

1

A loop will solve your problem since the items inserted in the array are in different positions:

const arr = [1, 2, 4, 5, 7]

// Adicione a [[posição1, valor1], [posição2, valor2]...]
const data = [[2, 3], [5, 6]];
data.forEach(a => arr.splice(a[0], 0, a[1]));

console.log(arr);

  • Show!!! Thank you very much!!! It would be possible to do this by going through the array with the map method()?

  • @Senaoliveira is possible but I do not know if it is the best choice. Example: [[2, 3], [5, 6]].map(a => arr.splice(a[0], 0, a[1])); The map returns an array as a result after processing each item of the source array. Since you don’t need this return, I don’t know if it is the most indicated one. I believe that the forEach is best suited for this problem

  • Perfect, thank you very much for the explanation!!!

  • @Senaoliveira map only makes sense if you want to turn all the elements of the array into something else. But in this case you are inserting elements into the array, and not transforming existing values, so map makes no sense in this case

  • @hkotsubo Show, thank you so much for the tip!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.