skip to Main Content

Suppose you have an array with values ​​in it:
let users = ["3" ,"4"];
And we want when new values ​​are added to it:
let newUsers =[ "5" , "6"];
users.push(newUsers)

Delete previous values, not add to them.

???
I would appreciate it if you could help me.

3

Answers


  1. Just clear the array:

     let users = ["3" ,"4"]; 
     let newUsers =[ "5" , "6"]; 
     users.length = 0;
     users.push(...newUsers);
     console.log(users);

    You could use splice also:

     let users = ["3" ,"4"]; 
     let newUsers =[ "5" , "6"]; 
     users.splice(0, users.length, ...newUsers);
     console.log(users);

    Note that if newUsers are bigger than about 100000 items you will get "Uncaught RangeError: Maximum call stack size exceeded". So you might want add item by item:

     let users = ["3" ,"4"]; 
     let newUsers =[ "5" , "6"]; 
     users.length = 0;
     newUsers.forEach(item => users.push(item));
     console.log(users);
    Login or Signup to reply.
  2. If you plan to replace the content of the array more than one time, you could write a function for that:

        let users = ["3" ,"4"]; 
        let newUsers =[ "5" , "6"];
    
        function addNewUsers(newArr){
            users = []
            users.push(...newArr)
        }
    
        addNewUsers(newUsers) // everytime you call this function with the content of the new array, the users array gets replaced with that content.
    
        console.log(users)
    

    But keep the Maximum call stack size (from the previous answer) in mind.

        let users = ["3" ,"4"]; 
        let newUsers =[ "5" , "6"];
    
        function addNewUsers(newArr){
            users = []
            newArr.forEach(item => users.push(item));
        }
    
        addNewUsers(newUsers) // everytime you call this function with the content of the new array, the users array gets replaced with that content.
    
        console.log(users)
    
    
    Login or Signup to reply.
  3. Just assign the newUsers variable to users and you are good to go.

    let users = ["3", "4"];
    let newUsers = ["5", "6"];
    
    users = newUsers;
    
    console.log(users); 
    

    This will work, but if you have any other requirements then please define too.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search