Conversion of for loops to "for each" - javascript

Have been stuck on this for a while:
I tried converting the code below to for each statements,and i ended up with errors.
ChartClass.prototype.dataTranslatorLine = function(data) {
jsonLength = Object.keys(data).length;
for (j = 0; j < jsonLength; j += 2) {
var innerObjArray = new Array();
positionNumber = Object.keys(data[j].position).length;
for (k = 0; k < positionNumber; k++) {
var obj = {};
obj.x = data[j].position[k];
obj.y = data[j + 1].position[k];
innerObjArray.push(obj);
}
dataArray.push(innerObjArray);
}
return dataArray;
};
Can anyone help me out with this?
Check out my fiddle here

I'm not entirely sure what is going on, but this should be a pretty direct translation to using forEach.
ChartClass.prototype.dataTranslatorLine = function(data) {
var dataArray = [];
Object.keys(data).forEach(function(key, idx) {
if (idx % 2 === 1) {
return;
}
var innerObjArray = [];
Object.keys(data[idx].position).forEach(function(key2, idx2) {
var obj = {
x: data[idx].position[idx2],
y: data[idx + 1].position[idx2]
};
innerObjArray.push(obj);
});
dataArray.push(innerObjArray);
});
return dataArray;
};
A couple of notes though: if data is an array, there is no need to call Object.keys on it, just go directly for the iteration; this code is rather convoluted, and I would think that with some work on the data structure being passed in could make more sense; and a for loop may be better for you situation instead of the forEach loop since you are primarily working on index instead of doing stuff just with the values.
EDIT:
After looking at your data structure this is a quick and dirty way to do it, but I still suggest you rework how you are storing your data into something that makes more sense.
ChartClass.prototype.dataTranslatorLine = function(data) {
for (var i = 0; i < data.length; i += 2) {
x = data[i].position;
y = data[i + 1].position;
var innerObj = [];
for (var j = 0; j < x.length; j++) {
innerObjArray.push({
x: x[j],
y: y[j]
});
}
dataArray.push(innerObj);
}
return dataArray;
};
The forEach doesn't buy you anything since you are working with indexes, not just the contents of the array. As for what key is in Object.keys(data).forEach(function(key, idx) { for you it will be the strings 'name' and 'position' since you are iterating over the keys of the object. Also, if (idx % 2 === 1) { return; } is how it is mimicking the j += 2 from your original for loop, basically exiting the function if it is an odd index.

Related

How to push to an array values from inside an arrow function

I'm trying to push to an array even numbers inside an arrow function but I don't how to push it in to that array.
My code:
var arrayEvenNumbers = [];
var evenNumbers = (arrayEvenNumbers) => {
for (i = 2; i <= 20; i++) {
if (i % 2 == 0) {
arrayEvenNumbers.push(i);
}
}
}
console.log(evenNumbers(arrayEvenNumbers));
Really I'm a beginner and I've learned a bit, but I'm trying my best
Hope someone could help me to improve
Also I don't know if I'm sending the arguments properly
And I'm not native english speaker so excuse if I can't express correctly :)
this way
var arrayEvenNumbers = [];
const evenNumbers = arr =>
{
for (let i = 2; i <= 20; i++)
if (i % 2 == 0) arr.push(i);
return arr
}
console.log( evenNumbers(arrayEvenNumbers) )
console.log( arrayEvenNumbers )
evenNumbers pushes it correctly, but returns undefined. You're probably looking to do:
evenNumbers(arrayEvenNumbers);
console.log(arrayEvenNumbers);
this is the code you've forgotten the return statement:
var freeArr = [];
var evenNumbers = (arr)=>{
for(i = 2; i <= 20; i++){
if(i % 2 == 0){
arr.push(i);
};
};
return(arr);
};
console.log(evenNumbers(freeArr));

How to programmatically create 3D array that increments to a defined number, resets to zero, and increments again?

Starting with this initial 2D array:
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
I need to create this 3D array programmatically:
var fullArray = [
[[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]],
[[3,4],[0,1],[5,6],[2,3],[6,7],[3,4]],
[[4,5],[1,2],[6,7],[3,4],[0,1],[4,5]],
[[5,6],[2,3],[0,1],[4,5],[1,2],[5,6]],
[[6,7],[3,4],[1,2],[5,6],[2,3],[6,7]],
[[0,1],[4,5],[2,3],[6,7],[3,4],[0,1]],
[[1,2],[5,6],[3,4],[0,1],[4,5],[1,2]],
[[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]],
[[3,4],[0,1],[5,6],[2,3],[6,7],[3,4]],
[[4,5],[1,2],[6,7],[3,4],[0,1],[4,5]],
[[5,6],[2,3],[0,1],[4,5],[1,2],[5,6]]
];
See the pattern?
On each pair, the [0] position should increment to 6 (from any starting number <= 6) and then reset to 0 and then continue incrementing. Similarly, the [1] position should increment to 7 (from any starting number <= 7) and then reset to 1 and then continue incrementing.
In this example, there are 10 2D arrays contained in the fullArray. However, I need this number to be a variable. Something like this:
var numberOf2DArraysInFullArray = 12;
Furthermore, the initial array should be flexible so that initialArray values can be rearranged like this (but with the same iteration follow-through rules stated above):
var initialArray = [[6,7],[2,3],[5,6],[4,5],[1,2],[6,7]];
Any thoughts on how to programmatically create this structure?
Stumped on how to gracefully pull this off.
Feedback greatly appreciated!
Here's a solution, I've separated the methods, and I made it so if instead of pairs it's an N size array and you want the [2] to increase up to 8 and reset to 2, if that's not needed you can simplify the of the loop for(var j = 0; j < innerArray.length; j++)
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
var create3DArray = function(array, size){
var newArray = [initialArray];
for(var i = 0; i < size; i++)
{
newArray.push(getNextArrayRow(newArray[i]));
}
return newArray;
}
var getNextArrayRow = function(array){
var nextRow = [];
for(var i = 0; i < array.length; i++)
{
var innerArray = array[i];
var nextElement = [];
for(var j = 0; j < innerArray.length; j++)
{
var value = (innerArray[j] + 1) % (7 + j);
value = value === 0 ? j : value;
nextElement.push(value);
}
nextRow.push(nextElement);
}
return nextRow;
}
console.log(create3DArray(initialArray,3));
Note, the results from running the snippet are a bit difficult to read...
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
var numOfArrays = 10;
// get a range array [0, 1, 2, ...]
var range = [];
for (var i = 0; i < numOfArrays; i++) {
range.push(i);
}
var result = range.reduce(function(prev, index) {
if (index == 0) {
return prev;
}
prev.push(transformArray(prev[index - 1]));
return prev;
}, [initialArray])
console.log(result);
function transformArray(arr) {
return arr.map(transformSubArray)
}
function transformSubArray(arr) {
return arr.map(function(val) {
return val == 7 ? 0 : val + 1;
})
}
Here's a pretty simple functional-ish implementation

getting javascript error while iterating through array

function sortproducts(filprodlist)
{
var prod;
var k = 0;
for (i = 0; i < filprodlist.length; i++) {
var k = i + 1;
var p=filprodlist[i].EntityKey.substr(filprodlist[i].EntityKey.length - 1);
var p2=filprodlist[k].EntityKey.substr(filprodlist[k].EntityKey.length - 1);
if ( p>p2) {
temp = filprodlist[k];
filprodlist[k] = filprodlist[i];
filprodlist[i] = temp;
}
}
rederProduct(filprodlist);
}
while executing above code getting following error
TypeError: filprodlist[k] is undefined
Reason
On last iteration, when i is at last element of array. You are fetching are using var k = i + 1;, where k doesn't exists. Thus you are getting the error.
So Use
for (i = 0; i < filprodlist.length - 1; i++) {
instead of
for (i = 0; i < filprodlist.length; i++) {
Don't var inside loops, blocks don't have scope in JavaScript, var every variable you want to use in one var statement. End your loop when the highest index reaches the end (k). You can move k into the for's iterate step because you're really iterating with this, too.
function sortproducts(filprodlist) {
var prod, i, k, p, p2, temp;
for (i = 0, k = 1; k < filprodlist.length; ++i, ++k) {
p = filprodlist[i].EntityKey.substr(filprodlist[i].EntityKey.length - 1);
p2 = filprodlist[k].EntityKey.substr(filprodlist[k].EntityKey.length - 1);
if (p > p2) {
temp = filprodlist[k];
filprodlist[k] = filprodlist[i];
filprodlist[i] = temp;
}
}
rederProduct(filprodlist);
}
A different way to do it is forget k all together, start from i = 1 and use i - 1 and i, this means you're iterating with less variables so it might be easier for you to follow the code in your mind.
Let's say filprodlist has 10 items. Then the items are indexed 0-9 and Your i goes through 0-9. In every iteration You define k = i + 1. So in the last iteration i = 9, k = 10 and You are trying to access filprodlist[10] which doesn't exist (returns undefined). Solution is in #Satpal's answer.

Pushing value into a multidimensional array

I have surfed the problem but couldn't get any possible solution ..
Let's say i have a var like this
var data = [
{
'a':10,
'b':20,
'c':30
},
{
'a':1,
'b':2,
'c':3
},
{
'a':100,
'b':200,
'c':300
}];
Now , i need a multidimensional array like
var values = [[10,1,100], //a
[20,2,200], //b
[30,3,300]]; //c
What i have tried is
var values = [];
for(var key in data[0])
{
values.push([]); // this creates a multidimesional array for each key
for(var i=0;i<data.length;i++)
{
// how to push data[i][key] in the multi dimensional array
}
}
Note : data.length and number of keys keeps changing and i just want to be done using push() without any extra variables. Even i don't want to use extra for loops
If you guys found any duplicate here , just put the link as comment without downvote
Try this:
var result = new Array();
for(var i = 0; i < data.length; i++) {
var arr = new Array();
for(var key in data[i]) {
arr.push(data[i][key]);
}
result.push(arr);
}
also if you don't want the 'arr' variable just write directly to the result, but in my opinion code above is much more understandable:
for(var i = 0; i < data.length; i++) {
result.push(new Array());
for(var key in data[i]) {
result[i].push(data[i][key]);
}
}
Ok, based on your comment I have modified the the loop. Please check the solution and mark question as answered if it is what you need. Personally I don't understand why you prefer messy and hard to understand code instead of using additional variables, but that's totally different topic.
for(var i = 0; i < data.length; i++) {
for(var j = 0; j < Object.keys(data[0]).length; j++) {
result[j] = result[j] || new Array();
console.log('result[' + j + '][' + i + ']' + ' = ' + data[i][Object.keys(data[i])[j]])
result[j][i] = data[i][Object.keys(data[i])[j]];
}
}

loop different arrays javascript

Hello there am trying to save news tweets into three different array which are dynamically created.
am finding trouble when i want to get the text from each one of those array and make another request to twitter.
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
news_array[i] = [{user:user,date:date,profile_img:profile_img,text:text,url:url}];
}
for (var i = 0; i < news_array.length; i++) {
for (var x=0; x<i.length; x++){
console.log(news_array[i][x].user);
}
}
});
}
It doesn't show anything on the console.log.
thanks for the help!!!!!
First, make sure that your count is smaller than the data array's length, otherwise this could lead to some undefined values:
for (var i = 0; i < count && i < data.length; i++) …
Then, why are you creating all those one-element-arrays in the news_array? Just use only objects.
This would solve your actual issue: You are looping wrong over those inner arrays. The correct code would be
for (var i = 0; i < news_array.length; i++) {
for (var x = 0; x < news_array[i].length; x++){
console.log(news_array[i][x].user);
}
}
Also, you should indent your code properly. You have some odd braces around, which don't make the code readable.
The problem is the x<i.length in the for loop near the end. i is a number, so it doesn't have a length. You probably meant x < news_array[i].length.
You may try the following:
Use the push method to append elements / data in your array new_array
Use only 1 loop for to display the user value on console
So your code will be something like this:
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
// Pushing your elements in your array, 1 by 1
news_array.push({user:user,date:date,profile_img:profile_img,text:text,url:url});
}
// Here you only need 1 loop!
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i][x].user);
}
});
}
First thing is i would loop the first one till data.length rather than count because its an api and it "might" or "might not" return all the data. So it will be fool proof to loop till data.length
And your problem is with i.length
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i].user);
}
this should work. not sure why you had to loop through a loop.

Categories

Resources