Question

I have an Array (oldArray) of 120 objects. I want to make another Array (newArray) whose first element is the first element of oldArray. Seems simple enough, except that my outputs are not as expected.

var obj = oldArray[0];
newArray[0] = obj;
console.log(obj);
console.log(newArray);
console.log(newArray[0]);
console.log(oldArray);
console.log(oldArray[0]);

obj, newArray[0], and oldArray[0] all produce the same result in my console -- the single object that I want to work with.

newArray however shows all objects of oldArray, not just the one that I thought obj contained. newArray.length == 1. Console displays: [Object]

oldArray is my original array. oldArray.length == 120. Console displays [Object, Object, ...]

I have tried many things and did not expect to get hung up on this. I thought it would have been newArray.push(oldArray[0]) or maybe newArray[0] = oldArray.splice(0,1) but everything I attempt seems to be creating the same issue.

Is there some kind of special trick for working with arrays of Objects?

Thanks!

Was it helpful?

Solution

I've tried replicating your issue and these are my results:

var oldArray = ['a','b','c','d'];
var newArray = [];

var obj = oldArray[0]; // store the first value in a new variable
newArray[0] = obj; // push the variable's value to the first index of the new array

console.log(obj);
    // 'a'
console.log(newArray);
    // ['a']
console.log(newArray[0]);
    // 'a' (the same as obj)
console.log(oldArray);
    // ["a", "b", "c", "d"]
console.log(oldArray[0]);
    // 'a'

Based on the scope of the script and the data in oldArray, these is correct behaviour. Either your test case isn't reduced properly or the problem isn't reflected by your question.

Since I was testing with strings and not objects, there may be some differing behaviour in your specific use case, but giving some sample data about the contents of oldArray would greatly help your cause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top