Jan
Jan

Reputation: 3401

Javascript: moving elements in an array

var array = ["object1","object2","object3","object4","object5"];
var copy = array.slice();
copy.forEach(function(value) {
 if(value === "object3"){
  value = "newObject3"

 }
});

console.log(copy );

If i want to move object3 in the array to the first index, after i assigned it a new value. How do I do it? and Whats the most effective and less time? any libraries like lodash can be used.

Upvotes: 0

Views: 76

Answers (1)

Weedoze
Weedoze

Reputation: 13953

var array = ["object1", "object2", "object3", "object4", "object5"];
var copy = array.slice();
copy.forEach(function(value, index, theArray) {
  if (value === "object3") {
    theArray[index] = theArray[0];
    theArray[0] = "newObject3";
  }
});

console.log(copy);

Upvotes: 1

Related Questions