0

I am looking to copy the substring of a string array into a new array without creating references. This is giving me a headache yet this should be fairly simple.

I tried NewArray[n] = OldArray[n].substr(x,y).slice(0) inside a loop and does not work. (I need to do a NewArray.sort() afterwards).

For the sake of example, say I got an OldArray with 2 elements:

['River', 'Lake']

I want the new array to be made of the first 2 characters (substring) of the old one such that:

['Ri', 'La']
0

2 Answers 2

1

copy the substring of a string array into a new array without creating references

Strings are primitive values in JavaScript, not Objects. There will be no reference when assigning the values of the old into the new array, especially when creating new strings with substr. The slice(0) you've used is superfluous when used with strings, and not necessary on arrays in your case, too.

Your code should work:

var oldArray = ["River", "Lake"];

var newArray = [];
for (var i=0; i<oldArray.length; i++)
   newArray[i] = oldArray[i].substr(0,2);

// newArray: ["Ri", "La"]
4
  • One day, in a distant future, we'll be using ECMAScript 5's Array.map for this. :P Commented Jul 11, 2012 at 19:54
  • Thank you! I finally noticed that indeed the error was a bit lower in the code. I tested the sort and the problem is int the treatment of the output. Commented Jul 11, 2012 at 20:06
  • you could also just use newArray.push(oldArray[i].substr(0,2)); Commented Jul 11, 2012 at 20:08
  • @MattiasBuelens: Yes, but I think var newArray=oldArray.map(function(str){return str.substr(0,2);}); is a little overhead here. The loop will be much faster. Commented Jul 11, 2012 at 20:10
-1

This worked for me. Thanks @Bergi

const newArray = oldArray.map( str => str.substr(0,2) ); 
0

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.