I built the following for Loop and wanted to ask if there is a way to simplify it:
//data contains an array
var i = 0;
if(data.length >= 1) {
i = 1;
}
for (i; i <= data.length; i++) {
$('#img-thumb-id' + i).attr('src', data[i-1]);
}
I see that jQuery is used here, so you can use $.each
$.each(data, function(i, item){
var iteration = +i+1;
$('#img-thumb-id' + iteration).attr('src', item);
});
if you want to use vanilla JavaScript (no jQuery at all)
for (var i; i < data.length; i++) {
var iteration = +i+1;
document.getElementById('img-thumb-id'+iteration).src = data[i];
}
Or you can use:
for (var i in data) {
document.getElementById('img-thumb-id'+(+i+1)).src = data[i];
}
if(typeof data!=="undefined" && data && data.length>0) {
for (var i=0; i < data.length; i++) {
$('#img-thumb-id' + (i+1)).attr('src', data[i]);
}
}
The loop is fine, but I don't see why you don't just do:
if(data !== null){
for (var i = 0; i < data.length; i++) {
$('#img-thumb-id' + (i + 1)).attr('src', data[i]);
}
}
You don't need to do the first block of code in your question. It is more clear to people reading your code if you just do a standard for-loop starting from 0 and going up to the object.length.
You may also try this :
data.forEach(function(item, index){
$('#img-thumb-id' + (index+1)).attr('src', item);
});
Use simple foreach loop in JavaScript
//for eg. data array may be
var data = [1,2,3,4];
data.forEach(function(item, index){
$('#img-thumb-id' + (index+1)).attr('src', item);
});
Related
I have this AngularJS service.
demoService.getDemoData($scope.countEP).then(function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
$scope.allEditorPicks.push(data[i]);
}
});
In this case,allEditorPicks is an array i have defined at the top of the code as follows.
$scope.allEditorPicks = [];
Here's the problem, when I'm using this array and printing these data, the array has same items. Duplicating. So I need a way to check existing items and stop adding them in that allEditorPicks array. We need to do this inside the for loop. I tried adding another loop inside the for loop and read the allEditorPicks array and check. But that doesn't work too.
demoService.getDemoData($scope.countEP).then(function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < $scope.allEditorPicks.length; j++) {
if ($scope.allEditorPicks[j].itemName == data[i].itemName) {
console.log("Item Exists")
} else {
$scope.allEditorPicks.push(data[i]);
}
}
}
});
This is the solution I tried. My browser got freezes and stopped working when I run this code. Please give me a solution.
first, sort the array by itemName and then remove the duplicates according to the order.
data = data.sort(function(a,b){
return a.itemName - b.itemName;
});
for (var i = 0; i < data.length; i++) {
if(data[i].itemName === data[i++].itemName){
console.log("Item Exists");
}else {
$scope.allEditorPicks.push(data[i]);
}
}
Try this :
demoService.getDemoData($scope.countEP).then(function (data) {
for(let i = 0; i < data.length; i++){
let found = $scope.allEditorPicks.find(elt => {
return elt.itemName === data[i].itemName;
});
if(!found){
$scope.allEditorPicks.push(data[i]);
}
}
})
Hi I am developing one jquery application. I am trying to compare the two arrays. For example,
Firstarray=["Mike","Jack"];
SecondArray=["Mike","Jack","Andy","Cruz"];
Whenever we compare above two arrays I want to return the strings which exists in both arrays or which are common to both arrays!
I tried as below. This piece of code is not working.
for (var i = 0; i < Firstarray.length; i++) {
for (var j = 0; j < SecondArray.length; j++) {
if (Firstarray[i] == SecondArray[j]) {
alert('found ' + SecondArray[j]);
return;
}
}
}
Can anyone help me in this regards! Thank you very much.
You can use indexOf() function
Firstarray=["Mike","Jack"];
SecondArray=["Mike","Jack","Andy","Cruz"];
var result = new Array();
for (var i = 0; i < Firstarray.length; i++) {
if(SecondArray.indexOf(Firstarray[i])>=0){
result.push(Firstarray[i]);
}
}
console.log(result);
Here is a solution using Array.prototype.filter and Array.prototype.some along with some ES6 flavor thrown in - see demo below:
var firstArray=["Mike","Jack"];
var secondArray=["Mike","Jack","Andy","Cruz"];
var result = secondArray.filter(a => firstArray.some(b => a === b));
console.log(result);
check this How can I find matching values in two arrays?
Array.prototype.diff = function(arr2) {
var ret = [];
this.sort();
arr2.sort();
for(var i = 0; i < this.length; i += 1) {
if(arr2.indexOf( this[i] ) > -1){
ret.push( this[i] );
}
}
return ret;
};
var FirstArray=["Mike","Jack"];
var SecondArray=["Mike","Jack","Andy","Cruz"];
var commonArray = Array();
var count=0;
for (var i=0; i<FirstArray.length; i++) {
for (var j=0;j< SecondArray.length;j++) {
if (FirstArray[i] == SecondArray[j]){
commonArray[count]=FirstArray[i];
count++;
}
}
}
console.log(commonArray);
Try changing few things in your code :
var Firstarray=["Mike","Jack"];
var SecondArray=["Mike","Jack","Andy","Cruz"];
var matchedData = [];
for (var i = 0; i < Firstarray.length; i++) {
for (var j = 0; j < SecondArray.length; j++) {
if (Firstarray[i] == SecondArray[j]) {
matchedData.push(SecondArray[j]);
}
}
}
alert(matchedData);
working fiddle :
https://jsfiddle.net/o3brcsvw/
try this
var Firstarray=["Mike","Jack"];
var SecondArray=["Mike","Jack","Andy","Cruz"];
var matchedData = [];
for (var i = 0; i < Firstarray.length; i++) {
for (var j = 0; j < SecondArray.length; j++) {
if (Firstarray[i] == SecondArray[j]) {
//alert('found ' + SecondArray[j]);
matchedData.push(SecondArray[j]);
}
}
}
return matchedData;
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.
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]];
}
}
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.