Hei, I have an array containing some empty strings and some strings with content.
I want to slice down the first 5 letters of those which are not empty strings, and put them into a new array. I also want to keep the empty ones.
example:
myArray = [ "","","123456789","","",""];
var newArray = ["","","12345","","",""]
I tried with for loop with if inside if the myArray[i] is empty then don't do substr(), but I get an error that it is not a function.
I actually don't need to put it into a new array, I just want to put the myArray(i).subsrt(5) value into a splice(), but then I get the error:
VM750:82 Uncaught TypeError: Cannot read property 'substr' of undefined
ES6 with array.map
myArray = [ "","","123456789","","",""];
var newArray = myArray.map((s) => s.substr(0, 5))
It's hard to know what your exact problem is without seeing all of your code, but here is a for loop that goes over all the elements in the first array and takes the first 5 or fewer characters of each string to insert into a new array.
myArray = [ "","","123456789","","",""];
var newArray = [];
for(var i = 0; i < myArray.length; i++) {
newArray.push(myArray[i].substr(0,5));
}
exactly what #le_m says:
myArray = [ "","","123456789","","",""];
var newArray = myArray.map(e => e.substr(0, 5));
You need to use substr for non-empty items:
Like this:
myArray = [ "","","123456789","","",""];
for(var i = 0; i < myArray.length; i++) {
temp = myArray[i];
if (temp && temp != "")
myArray[i] = temp.substr(0, 5);
else
myArray[i] = "";
}
Related
I am trying to push objects into an array inside a for loop. The expected data structure is
[{"valueItem":"item0"}, {"valueItem":"item1"}, {"valueItem":"item2"}, {"valueItem":"item3"}, {"valueItem":"item4"}]
The code I have is
var arr = [];
var obj = {};
for(var i = 0; i < 5; i++){
arr.push(obj.valueItem = 'item'+i);
}
console.log(arr)
But the what I get back is
["item0", "item1", "item2", "item3", "item4"]
What am I doing wrong?
try:arr.push({"valueItem":"item"+i});
Ok, to clarify, you have to push an object in your array to get your expected array.
push(obj.valueItem = 'item'+i) works sortof because you are assigning inside push.
The below works ;)
var arr = [];
for(var i = 0; i < 5; i++){
var obj = {};
obj.valueItem = 'item' + i;
arr.push(obj);
}
console.log(arr)
By doing this arr.push(obj.valueItem = 'item'+i);
you are not pushing obj into the array, you are making an assignment
obj.valueItem = 'item'+i
the result of an assignment is the returned value, in this case it is item+i,
to push objects into an array do this
arr.push({
valueItem: "item0"
})
First define object, then push it to array:
var arr = [];
for(var i = 0; i < 5; i++){
arr.push({valueItem: 'item'+i});
}
console.log(arr)
Based on your try:
var arr = [];
for(var i = 0; i < 5; i++){
var obj = {};
obj.valueItem = 'item'+i
arr.push(obj);
}
console.log(arr)
Looks like you're not actually creating a new object for each loop. Maybe try:
arr.push( { valueItem: 'item'+i } );.
The {} will create a new hash object, which we would push onto the array.
In your inital code you only made one object, so the thing you were pushing was the return value of obj.valueItem='item'+i. Since the return value of a string assignment would be the actual string, you were just creating an array of strings.
Your expected result has a different object for each element. Even though they are are similar in that they have a valueItem proprerty, they are all different. So you need to create a new one on each loop iteration. You need
arr.push({valueItem:"item"+i});
which creates a new one each time.
I searched a lot, but I could not get a satisfactory answer on the net. In javascript, how do I add an array into another multidimensional array at a particular position based on a key value?
finalArray = []; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = [];
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp; // This gives an error
}
basically, I have
group = [ 'alpha' ,'beta', 'gamma' ]; //this array generated dynamically
my finalArray should be like,
finalArray['alpha'] = [ some records ];
finalArray['beta'] = [ some records ];
....
As far as I know, the way to add array into another array is to use .push() method, but that creates indices as 0, 1, 2... which is not desired. Please help me out
You have to use Object instead of Array. Make the following changes in the code
finalArray = {}; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = {};
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp;
}
console.log(finalArray); //to see the object key value structure
now you can reference the values in finalArray with group[i] name. Hope this helps
You have to define your finalArray variable as Object instead of and Array:
var finalArray = {}; //or better in your case finalMap
var group = [ 'alpha' ,'beta', 'gamma' ];
var finalArray = {}; //declare it object as you dont want 0,1 indexes
for (var index in group){
finalArray[group[index]] = "some records/arry of records"
}
console.log(finalArray);
DEMO
How can I create a multidimensional array in JavaScript?
I have:
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar = [];
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
If I do:
groupsData.name_of_bar[0]
I get errors:
TypeError: Cannot read property '0' of undefined
TypeError: Cannot set property 'a' of undefined
What am I doing wrong?
JavaScript doesn't support multidimensional arrays per se. The closest you can come is to create an array where the values in it are also arrays.
// Set this **outside** the loop so you don't overwrite it each time you go around the loop
groupsData.name_of_bar = [];
for (var i = 0; i < m; i++){
// Create a new "array" each time you go around the loop
// Use objects, not arrays, when you have named properties (instead of ordered numeric ones)
groupsData.name_of_bar[i] = {};
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
Each iteration through the loop, you are doing groupsData.name_of_bar = [];. This removes whatever else is already in there and replaces it with a blank array.
Also, when you do groupsData.name_of_bar[i]['a'], you need to create groupsData.name_of_bar[i] first.
A way to do this is:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy: data[i].xy,
});
}
Note that in JavaScript, arrays can only be numerically indexed. If you want string indexes, you need to use an object.
Also, if there are no other values in data[i], then you can simplify this even further by doing:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push(data[i]);
}
Heck, why not just use groupsData.name_of_bar = data; and lose the loop altogether?
The way you are declaring your objects are a little off. It looks like you are attempting to create an array of objects.
var groupsData = {name_of_bar: []},
m = 4,
i = 0;
for(; i < m; i++) {
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy = data[i].xy
});
}
Consider this, I have a JScript array of arrays.
I want to copy a given index of the array into another array using the same index.
So for example:
MyArray = {[0] = Array, [1] = Array, [2] = Array}
I want to copy the 3rd index [2] into another array, such that the first index is not '0' but '2'.
Giving Me:
MyNextArray[2] = {Array}
Apologies for the pseudo code.
Can I make the copy or do I have to first initialize the array and then set a custom index?
Thanks in advance!
MyArray = {[0] = Array, [1] = Array, [2] = Array}
var MyNewArray = sortRay(MyArray, 2);
function sortRay(Ray, firstNr){
MyNextArray = new Array();
MyNextArray[0] = Ray[firstNr];
for(var i = 0, j = 1; i <= Ray.length, i++){
if(i == firstNr){i++, j = 0;}
MyNextArray[i+j] = MyArray[i];
}
return MyNextArray;
}
shld work
First I have an array like:
arr = [[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a]]
I can 'flatten' it using
arr = Array.prototype.concat.apply([],arr)
or using a for-next loop and push.apply
Then I got:
[r,g,b,a,r,g,b,a,r,g,b,a,r,g,b,a,r,g,b,a]
How do I get it back to its original format as easy as possible?
var newArr = [];
while(arr.length){
newArr.push(arr.splice(0,4));
}
Something like this, perhaps:
var old = [];
for (var index = 0; index < arr.length; index+= 4)
old.push( arr.slice(index, index + 4) );