0
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.

5
  • array.prototype.push is what you seek. Commented Nov 17, 2016 at 13:52
  • 2
    This subject is discussed quite well in this question: stackoverflow.com/questions/5306680/… Commented Nov 17, 2016 at 13:54
  • And those aren't really objects, but strings ? Commented Nov 17, 2016 at 13:55
  • 1
    jsfiddle.net/5kdhtyt7 Commented Nov 17, 2016 at 13:58
  • thank you for the links! Commented Nov 17, 2016 at 14:01

1 Answer 1

1

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);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.