Copy substring of string array into new array in Javascript - javascript

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']

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"]

This worked for me. Thanks #Bergi
const newArray = oldArray.map( str => str.substr(0,2) );

Related

Concatenating html object arrays with javascript

I'm attempting to merge two arrays made up of html objects. For some reason using .concat() will not work for me.
Here's a simple pen to demonstrate the problem: http://codepen.io/anon/pen/kIeyB
Note: I tried searching for something remotely similar but found nothing that answered my question.
I figure you can do this the ole fashion way using for-loops but I rather not re-invent the wheel.
var x = document.getElementById("hello");
var items = x.getElementsByClassName("one");
//alert(items.length);
var items2 = x.getElementsByClassName("two");
//alert(items2.length);
items = items.concat(items2);
//alert(items.length);
items and items2 are nodeList or HTMLCollection objects, not arrays. They do not contain a .concat() method. They have a .length property and support [x] indexing, but they do not have the other array methods.
A common workaround to copy them into an actual array is as follows:
// convert both to arrays so they have the full complement of Array methods
var array1 = Array.prototype.slice.call(x.getElementsByClassName("one"), 0);
var array2 = Array.prototype.slice.call(x.getElementsByClassName("two"), 0);
This can be also be done like this:
var allitems = [];
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("one"));
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("two"));
The allitems variable will be a single javascript Array containing all elements with class one & two.
What you have are HTMLCollections, which although behave like arrays, but are not arrays. See here: https://developer.mozilla.org/en/docs/Web/API/HTMLCollection:
..A collection is an object that represents a lists of DOM nodes..
In your case, you could concatenate these objects together into a new array:
var itemsnew;
var x = document.getElementById("hello");
var items = x.getElementsByClassName("one");
var items2 = x.getElementsByClassName("two");
itemsnew = Array.prototype.concat.call(items, items2);
Now, if you:
console.log(itemsnew);
Will return:
[HTMLCollection[1], HTMLCollection[1]]
And:
console.log(itemsnew[0][0]);
Will return:
<div class="one"></div>
document.getElementsByClassName doesn't return an array.
It returns NodeList which has length property.

What does empty array.slice(0).push(anything) mean?

I want to clone a new array from an existing one and push in an element.
Unfortunately, the existing array is an empty one, so it's like:
[].slice().push(65)
the output of above expression is 1.
Why is it 1?
Array#push() returns the length of the resultant array. Since you're pushing a single value onto an empty array, the length of the result will indeed be 1.
If you want to see the updated array as output, you'll need to save a reference to it since push() does not return a reference:
var arr = [].slice();
arr.push(65);
console.log(arr); // [ 65 ]
Changing my comment to an answer:
MDN push(): The push() method adds one or more elements to the end of an array and returns the new length of the array.
You need to do it in two steps, not one with that pattern.
var temp = [].slice();
temp.push(65);
console.log(temp);
If you want to do it in one line, look into concat()
var a = [1,2,3];
var b = [].concat(a,64);
console.log(b);

Create Array of arrays in Javascript

In Ruby you can make an array of arrays (which can represent a grid) by doing the following
#grid = Array.new(num_rows) {Array.new(num_columns)}
Is there an equivelent with Javascript?
Or do you need to create the first array and iterate over it, explicitly creating a new array at each index?
e.g.
this.grid = new Array(this.numRows);
for (var i = 0; i < this.numRows; i++) {
this.grid[i] = new Array(this.numColumns);
}
I am using Underscore.js so could leverage its methods if needs be
There may be something better in underscore, but the following will work. I used 3 and 4 because for the height/width just so I could see the results in this fiddle.
array = _.map(_.range(3), function(){return _.range(4)});
You might want to add the underscore tag to get some underscore eyes on the question.
In JavaScript you can have different objects at different elements of an array. It's as simple as
var myArray = new Array()
myArray[0] = new Array()
You can do that as many times as you like to set up size of the 2D space you want to create. Use loops to set them up if your space is large. I don't know what objects you want in your array or I'd be more specific.
It just as easy to access this structure as in any other language: myArray[58][12]
This question is also relevant.

How do array sizes work in Javascript

In JavaScript, if you set an array to be of size 5 ( var foo = new Array(5); ), is this just an initial size? Can you expand the number of elements after it is created. Is it possible to do something like this as well - arr = new Array() and then just assign elements one by one? Thanks in advance :-)
Yes it is just an initial size, and it is not required. If you don't use a single number, you can immediately populate.
It is also more common to use the simpler [] syntax.
var arr = ['something', 34, 'hello'];
You can set (or replace) a specific index by using brackets:
arr[0] = "I'm here replacing whatever your first item was";
You can add to the end by using push:
arr.push('add me');
There may be faster performance in some browsers if you do it like this instead:
arr[arr.length] = 'add me';
You can add something at any index.
You can remove an item completely using splice:
arr.splice(0, 1); // remove first item in the array (start at index 0, with 1 being removed)
When you give a new array an explicit size in javascript (using new Array(5)), you populate each index with value of undefined. It is generally considered better practice to instantiate using the array literal [] expression:
var arr = [];
Then, you can push new elements using push()
var arr = [];
arr.push('first value'):
arr.push('second value'):
Check out the MDC Array documentation for more info: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
Theres a few ways to declare and put values in an array.
First like what you want to do,
var myarr = new Array();
myarr[0] = 'element1';
myarr[1] = 'element2';
myarr[2] = 'element3';
Second way is to define them
var myarr =new Array("element1","element2","element3");
and third is similar to the second
var myarr =["element1","element2","element3"];
You can also check out https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array for a little more information about using the arrays as well. You could use push and pop if you wanted to as well.
If you use jquery or mootools they also have built-in functions to perform on arrays,
http://api.jquery.com/jQuery.each/ for instance.
Have a look at http://www.w3schools.com/js/js_obj_array.asp
var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab"; // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";
Check the documentation for Array, but the simple answer to your question is yes.
var arr5 = new Array(1, 2, 3, 4, 5); // an array with initial 5 elements
var arr = new Array(); // an array without initial
You can also use array literals:
var arr5 = [1, 2, 3, 4, 5];
var arr = [];
Arrays are dynamic in JavaScript. You don't have to initialize them with a certain length. In fact you should use the literal notation [] because of the Array constructor's ambiguity:
If you pass only one parameter to Array, it will set the array length to this parameter. If you pass more than one parameter, these elements are added to the array.
How is the size of the array determined?
The size of an array is the highest index + 1. This can be quite confusing. Consider this:
var arr = [];
arr[41] = 'The answer?';
console.log(arr); // [undefined, undefined, ..., 'The answer?']
console.log(arr.length) // 42
You can even set the length yourself by assigning a number to .length:
arr.length = 99;
If you now add a new element using arr.push(), it will get the index 100 and the length will increase. Whenever you add an element to the array via an index, it is tested whether arr.length is smaller than the index and updated accordingly. But it does not get smaller.
So in fact what var arr = new Array(5) is doing is setting the length of the array to 5. Nothing else.
For more information about creating and populating arrays, I suggest to read about it in the MDC JavaScript Guide.

How to manipulate string in an array

I have an array that contain some fields
like this
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_18
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_19
I want to create a new array or manipulate this array to contain only
sid = {25,26,27}
from
_SID_25
_SID_26
_SID_27
where sid will be my array containing sid's extracted from above array
with pattern _SID_
I have to do this in jquery or javascript
use jquery map + regexp
var arr= ['tl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_26_SortOrder_18',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_27_SortOrder_19']
var out = $(arr).map(function(){
return this.match(/SID_(.*?)_/)[1];
});
out should be an array of the values..
(assuming all the values in the array do match the pattern)
I would use regex here
var sid = []
var matches = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17".match(/_SID_(\d+)/);
if(matches) sid.push(parseInt(matches[1]));
This solution is totally reliant on the overall string form not changing too much, ie the number of "underscores" not changing which seems fragile, props given to commenter below but he had the index wrong. My original solution first split on "SID_" since that seemed more like a key that would always be present in the string going forward.
Given:
s = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25344_SortOrder_17"
old solution:
array.push(parseInt(s.split("SID_")[1].split("_")[0]))
new solution
array.push(parseInt(s.split("_")[7])

Categories

Resources