vignesh selvarathinam
vignesh selvarathinam

Reputation: 129

How to push the values in array based on position?

I am working on pushing the values in array.

My Exact Scenario:

If the array contains 2 values, after the push operation the pushed value has to come in between the 2 values(which is based on position).

I somehow did it using Pop the last value and Push the new value with poped value. Below is My code.

var fruits = ["Banana", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
    var pop = fruits.pop();
    fruits.push("Kiwi",pop);
    document.getElementById("demo").innerHTML = fruits;
}
<!DOCTYPE html>
<html>
<body>

<p>Click the button to add a new element to the array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
  
</body>
</html>

My code is Working Fine.But is there any better solution for that using Push method only (without using pop).

Thanks in advance.

Upvotes: 1

Views: 46

Answers (2)

Disha
Disha

Reputation: 832

Use splice method for it. see fiddle

fruits.splice(index, 0, item); 

will insert item into fruits array at the specified index

Upvotes: 2

Sajeetharan
Sajeetharan

Reputation: 222672

You are doing it in pure javascript,In angular

var app = angular.module('DemoApp', [])
app.controller('DemoController', function($scope) {
  var fruits = ["Banana", "Mango"];
  $scope.fruits = fruits;
  $scope.myFunction = function()
  {
    $scope.fruits.push("Kiwi");
  }
  console.log($scope.fruits);
});

DEMO

Upvotes: 1

Related Questions