-1

My first question was not really clear, sorry about that. So, I know about "split" method in JavaScript and now I want to add number to random array on a position that I can choose inside array, but without "split". Question is for understanding how algorithm "inside" "split" method is working. I wrote random array, so my idea is to use loop second times for a random array, create empty array add that number to position, then number that was before the position of our new number add to empty array and then got confused a bit.

var array1 = [];
for (var k= 0, t=100; k<t; k++){
    array1.push(Math.round(Math.random() * 300))
};

console.log(array1)
8
  • 3
    I need to add number (...) to position that i'm choosing... I don't see that. With this code you just generate an array of random numbers. How are you adding the number to the position (the one you're choosing)? Commented Jun 28, 2018 at 13:04
  • 1
    You can always use a loop and move everything manually. What have you tried to far? Why don't you want to use split (splice)? Or is this homework...? Commented Jun 28, 2018 at 13:05
  • 1
    Voting to close as the question you're asking is unclear. Please rephrase your question then edit your post. Commented Jun 28, 2018 at 13:07
  • 1
    @lealceldeiro My guess is he's helpfully giving us code that creates a random array so when we give him the solution, we don't also need to write that first... Commented Jun 28, 2018 at 13:08
  • 1
    I know algorithm with split method. But i'm interested how to do this without ready methods. Commented Jun 28, 2018 at 13:11

1 Answer 1

4

Not sure what your code has to do with the question, but you can use Array.prototype.splice() to add an element at a specified index

const arr = ['foo', 'bar', 'baz'];
arr.splice(1, 0, 'bam');
//         ^ index
console.log(arr);

Sign up to request clarification or add additional context in comments.

7 Comments

... it was faster to answer than to find the duplicate; now it's closed for good @Ivan
@bambam I found the duplicate by looking at OP's earlier questions :) I bet this is homework.
@bambam look at the comment posted by the OP (I know algorithm with split method. But i'm interested how to do this without ready methods). This might not be what he/she is looking for.
Agree with you @bambam. I'm just pointing that out, since the OP is (persistently) asking about something else, not splice or any other built in function. Of course I would use what's already implemented (like splice).
Yeah, sorry for not informative question, split method i know very well, but inside, i think, split method contains algorithm. So that was my question, how to add/delete elements from array without "split"
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.