how to loop through array with javascript - javascript

I its basic but I am new to javascript. I am trying to loop through the array and match the objects that == my key.
this is what i am using right now, it works but i am only matching the first object that matches, sometimes there will be multiple objects that match.
Here is what i have now
var chartSeries = chartService.getSeries();
var marker.options.subdivision.id = 1345
var matchingSeries = Enumerable.From(chartSeries).Where('x => x.id == "' + marker.options.subdivision.id + '"').ToArray();
var series = {
id: matchingSeries[0].id,
name: matchingSeries[0].name,
data: matchingSeries[0].data,
lineWidth: 5
};
I need to include a for loop to match all objects.
var subIdSeries = [];
var subId = marker.options.subdivision.id;
var series = {
id: matchingSeries[0].id,
name: matchingSeries[0].name,
data: matchingSeries[0].data,
lineWidth: 5
};
for (var i = 0; i < chartSeries.length; i++) {
if (subId == chartSeries.id) {
push.subIdSeries(subId)
}
}

Change
if (subId == chartSeries.id) {
push.subIdSeries(subId)
}
to
if (subId == chartSeries[i].id) {
subIdSeries.push(subId)
}

Without seeing the whole script, from what you have so far, I can suggest:
if (subId == chartSeries[i].id) {
subIdSeries.push(subId)
}

Related

Calling objects with numbers at the end in a for loop

This is a sample code of what I'm trying to work on. I think it's probably a simple thing but the teachers on the front end course I'm in don't have an answer for me (either in the "here's the format to use" or "here's the proper way to do what you're trying here".)
var part1 = {
type = 1,
}
var part2 = {
type = 2,
}
var part3 = {
type = 3,
}
var partArray = [part1, part2, part3];
var carArray = [];
var truckArray = [];
for (i = 0; i < partArray.length; i++) {
if (part[i].type === 1 || part[i].type === 2) {
carArray.push(part[i]);
}
if (part[i].type === 3) {
truckArray.push(part[i]);
}
}
You are doing a few things incorrectly. First is how you create the properties in your part objects. Second is you are accessing a variable that doesn't exist part. I know you are trying to access part1, part2, part3. The thing is you already have those in your array, so the easiest is to access through there. Try this:
var part1 = {
type: 1
}
var part2 = {
type: 2
}
var part3 = {
type: 3
}
var partArray = [part1, part2, part3];
var carArray = [];
var truckArray = [];
for (var i = 0; i < partArray.length; i++){
if (partArray[i].type === 1 || partArray[i].type === 2){
carArray.push(partArray[i])
}
if (partArray[i].type === 3){
truckArray.push(partArray[i])
}
}
console.log(carArray)
console.log(truckArray)
You are using part instead of partArray
for (i=0; i < partArray.length; i++){
if (partArray[i].type === 1 || partArray[i].type === 2){
carArray.push(partArray[i])
}
if (partArray[i].type === 3){
truckArray.push(partArray[i])
}
}

repopulating table with "filtered" data

See the code below.
I have a table populated with JSON data. The following is intended to clear the table and retrieve only the data with the last name criteria specified by the user.
So far, I'm successful in creating the filter criteria and wiping the table clean. However, I'm having trouble repopulating the table with the filtered results.
Possible hang-ups:
-the Regex: I'm new to RegExp with JS and I'm thinking the syntax is correct, but I'm not entirely sure. I'm also not sure if I'm able to use it the way I am (setting it: filterCriteria = new RegExp("^" + filter.value) and then calling on it to check if last_name object is equal to it: if (contacts.last_name === filterCriteria)
or even if the Regex is working properly, am I able to create a new array based on it the way I'm trying to in that If statement? I.e. is that enough to say, "Take only the objects with a last name that matches the criteria and throw them into a new array"?
Thanks for the help!
var filter = document.getElementById("filter");
filter.addEventListener("keydown", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
if ((xhr.readyState === 4) && (xhr.status === 200)) {
var contacts = JSON.parse(xhr.responseText).data,
filterCriteria = new RegExp("^" + filter.value),
i;
for (i = 0; i < contacts.length; i += 1) {
var contactTableBody = document.getElementById("contactTable").lastElementChild,
lastRow = contactTableBody.lastElementChild;
contactTableBody.removeChild(lastRow);
}
if (contacts.last_name === filterCriteria) {
var filterResults = [contacts];
for (i = 0; i < contacts.length; i += 1) {
contactTableBody = document.getElementById("contactTable").lastElementChild;
var newRow = [],
newNameCell = document.createElement("td"),
newPhoneCell = document.createElement("td"),
newEmailCell = document.createElement("td"),
newNameNode = document.createTextNode(contacts[i].last_name + ", " + contacts[i].first_name),
newPhoneNode = document.createTextNode(contacts[i].phone),
newEmailNode = document.createTextNode(contacts[i].email);
newRow[i] = document.createElement("tr");
newRow[i].id = "contact" + i;
newNameCell.appendChild(newNameNode);
newPhoneCell.appendChild(newPhoneNode);
newEmailCell.appendChild(newEmailNode);
newRow[i].appendChild(newNameCell);
newRow[i].appendChild(newPhoneCell);
newRow[i].appendChild(newEmailCell);
contactTableBody.appendChild(newRow[i]);
}
}
}
EDIT:
not 100% on the brace/bracket notation but that should give an idea on how the data is oriented
contacts = JSON.parse(XMLHttpResponse.responseText).data = { [
{ "first_name":"Jim", "last_name":"Cooper", "phone":"8435555555", "email":"jim#halpert.com" },
{ "first_name":"Jim", "last_name":"Aaron", "phone":"1234567890", "email":"jim#beam.com" },
{ "first_name":"Mark", "last_name":"Smith", "phone":"4567891236", "email":"mark#smith.com" },
{ "first_name":"Sally", "last_name":"Smith", "phone":"5469876622", "email":"sally#smith.com" },
{ "first_name":"Mary", "last_name":"Coppersmith", "phone":"6854895212", "email":"mary#coppersmith.com" }
] }
from Santosh initial comment:
I do not know the context, but shouldnt the contacts.last_name be
inside the for loop? Something like this contacts[i].last_name == filterCriteria. If you can the mock up data for contact or a jsfiddle,
it would help.
It was in fact a for loop that was needed. Thanks.

javascript + combine json arrays based on key,

I am trying to merger two json to one json. I don't want merge all keys, I added my code.
Code should be in javascript or node (underscore).
var json1 = [{user_id:1,friend_id:2,desc:'aaa'}, {user_id:3,friend_id:4,desc:'ccc'}, {user_id:1,friend_id:1,desc:'ccc'} , {user_id:1,friend_id:3,desc:'ccc'} ];
var json2 = [{reference_id:1,name:'A'},{reference_id:2,name:'B'},{reference_id:3,name:'C',age:30},{reference_id:4,name:'D'}];
Expecting Output:
output:
json1 = [{user_id:1,friend_id:2,desc:'aaa',user_name:'A',friend_name:'B'}, {user_id:3,friend_id:4,desc:'ccc',user_name:'C',friend_name:'D'}, {user_id:1,friend_id:1,desc:'ccc',user_name:'A',friend_name:'A'} , {user_id:1,friend_id:3,desc:'ccc',user_name:'A',friend_name:'C'} ];
Logic Js Code:
for (var i = 0; i < json1.length; i++) {
var user_id = json1[i].user_id;
var friend_id = json1[i].friend_id;
for (var j = 0; j < json2.length; j++) {
if (json2[j].reference_id == user_id) {
json1[i].user_name = json2[j].name;
}
if (json2[j].reference_id == friend_id) {
json1[i].friend_name = json2[j].name;
}
}
}
I attached my code in jsfiddle.Click Here
The same code should be convert into underscore.
You are repeating some effort here. Doesn't really matter if json2.length is small; but if it is large you will pay a penalty: you are looping over every element of json2 for every time you look at an element of json1. So instead, think of it this way:
var personMap = {};
json2.forEach(function(item) {
personMap[item.reference_id] = item.name;
});
json1.forEach(function(item) {
item.user_name = personMap[item.user_id];
item.friend_name = personMap[item.friend_id];
});
Your code in plain vanilla JS should work, except for "==" in the places where you've mistakenly put "=".
Replace these:
if (json2[j].reference_id = user_id) {
...
if (json2[j].reference_id = friend_id) {
...
with these:
if (json2[j].reference_id == user_id) {
...
if (json2[j].reference_id == friend_id) {
Try this is underscore:
_.map(json1, function(item){
var user_id = item.user_id;
var friend_id = item.friend_id;
_.map(json2, function(item2){
if (item2.reference_id == user_id) {
item.user_name = item2.name;
}
if (item2.reference_id == friend_id) {
item.friend_name = item2.name;
}
});
});

Values are not being saved to the array

I am pretty new to javascript and jquery. I currently have a xml file that I'm trying to parse by using jquery and javascript, but for some reason the values that I store on the array are not being saved.
var categories = new Array(); // Array for the categories
var data = {
categories: []
};
var sources = [
{
src:'',
title: '',
desc: ''
}];
var i = 0;
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
sources[i] = [];
sources[i].src = el.find('media\\:content, content').attr('url');
sources[i].title = el.find("title").text();
sources[i].desc = 'Moscone Center';
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
}
i++;
});
});
If i do console.log(categories) it prints all the categories on the array but if I do console.log(categories.length) I keep getting 0...
console.log(categories.length); // This should be outputting 5 but I keep getting 0 for the size.
for (var i=0; i<categories.length; i++) {
var category = {
name: categories[i],
videos: []
};
}
I appreciate any help that anybody can give me. Thanks
$.get function is asynchronous so you should try putting the logging inside the callback function.
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
....
});
console.log(categories.length);
});

Get Next and Previous Elements in JavaScript array

I have a large array, with non-sequential IDs, that looks something like this:
PhotoList[89725] = new Array();
PhotoList[89725]['ImageID'] = '89725';
PhotoList[89725]['ImageSize'] = '123';
PhotoList[89726] = new Array();
PhotoList[89726]['ImageID'] = '89726';
PhotoList[89726]['ImageSize'] = '234';
PhotoList[89727] = new Array();
PhotoList[89727]['ImageID'] = '89727';
PhotoList[89727]['ImageSize'] = '345';
Etc....
I'm trying to figure out, given an ID, how can I can get the next and previous ID... So that I could do something like this:
<div id="current">Showing You ID: 89726 Size: 234</div>
Get Prev Get Next
Obviously, if we're at the end or beginning of the array we just a message...
Why don't you add properties 'Prev' & 'Next' to that array?
PhotoList[89725] = new Array();
PhotoList[89725]['Prev'] = 89724;
PhotoList[89725]['Next'] = 89726;
PhotoList[89725]['ImageID'] = '89725';
PhotoList[89725]['ImageSize'] = '123';
This is just 'doubly-linked list' data structure.
Based on your example the IDs are sequential...
This is another way of writing your example. new Array() really isn't what you should be using because those are objects you are creating. Also, I left the numbers as strings, but I'm not sure why you would want to do that. You could add next and prev like kuy suggested
PhotoList[89725] = {ImageID: '89725',
ImageSize: '123'};
PhotoList[89725] = {ImageID: '89726',
ImageSize: '234',
Next: '89727',
Prev: '89725'};
PhotoList[89725] = {ImageID: '89727',
ImageSize: '345'};
All of these are accessible just like your other structure.
There's really no way other than to iterate through the possible ids sequentially until you find one which has an entry in your array. For example:
function findClosest(arr, id, increasing) {
var step = increasing ? 1 : -1;
for(var i=id+step; i>=0 && i<=max_id; i+=step)
if( arr[id] )
return id;
}
Obviously, this approach requires that you keep track of the max_id so that you don't iterate forever; here I assume that it's a global variable, but you might want to make it a parameter to the findClosest function. You'd call this function like so:
var prev = findClosest(arr, id, false);
var next = findClosest(arr, id, true);
I agree with the rest quotes you should be using objects not an array. Also make sure you create new arrays using the literal notation and not the new keyword with built in types. The new keyword is bad news and you could clobber the global object. Check out JSLint.
var a = new Array(); //bad dont use
var a = []; //this is the best way to create a new array
var o = {}; //create new objects like this
As for the problem at hand. Why not write a simple container that has its own internal counter?
function PhotoListContainer(PhotoList)
{
if(PhotoList === undefined)
throw("no photo list");
this.counter = 0;
var self = this;
this.current = function(){
return PhotoList[self.counter];
};
this.next = function(){
return PhotoList[self.counter + 1];
};
this.prev = function(){
return PhotoList[self.counter - 1];
};
// You could even write a function that loops each value from the current counter :)
this.each_from_counter = function(callback){
for(var i = self.counter; i < PhotoList.length; i++)
{
callback(PhotoList[i], i);
self.counter++;
}
};
}
//use
var pc = new PhotoListContainer(PhotoList);
pc.counter = 500;
pc.next(); //returns the 501st object
pc.prev(); //returns the 499th object
pc.each_from_counter(function(photo, index){
photo.somehting;
});
No arrays at all are better..
images = {
0: {
size: 12345, /* dont realy need as you can use JS to mesure the size. */
title: "day 1 on holiday"
},
1: {
size: 13549, /* dont realy need as you can use JS to mesure the size. */
title: "day 2 on holiday"
},
2: {
size: 16548, /* dont realy need as you can use JS to mesure the size. */
title: "day 3 on holiday"
},
}
for(x in images){
/* x = "the id of the image." */
url[] = "/images/" + x + ".png";
title[] = images[x].title;
size[] = images[x].size;
console.log("File: " + url[x] + " , Title: " + title[x] + " , Size: " + size + "bytes")
}
var sibNum = 0;
var sibList = [];
var prevSiblingID = false;
for (n in w) {
sibNum++;
sibList[n] = {
title : n,
prevSiblingID : prevSiblingID
};
if (prevSiblingID) {
sibList[prevSiblingID].nextSiblingID = n;
}
prevSiblingID = n;
};
sibList[prevSiblingID].nextSiblingID = false;
you can use grep function and calculate prev or next item of specified array:
object = $.grep(data, function(e) {
if(e.id == yourId) {
return data[data.indexOf(e) + 1]; // or -1 for prev item
}
});
i think your image list will come from DB so you may can try this code, this code is working for me.
<?
$prev="";
$next="";
$cur=0;
$i=0;
$pid=$_GET['pid'];
while($rowcon=mysql_fetch_assoc($result))
{
$arr[$i]=$rowcon['pid'];
if($rowcon['pid']==$pid)
{
$cur=$i;
}
$i++;
}
if($cur<$num_rows)
$next=$arr[$cur+1];
else
$next="";
if($cur>0)
$prev=$arr[$cur-1];
else
$prev="";
echo $prev." ".$cur." ".$next;
?>

Categories