how to itereate an json object in angularjs using for loop? - javascript

I have one array i want to iterate that in the iteration process we check one condition if condition is true we return one value otherwise we return else part I write some code but its not working.
the loop will not terminated if condition is true how can i do that cam anyone help me?
$scope.bgImages = []; //it having some objects
$scope.job = []; //it also having some objeccts
//if both elements are matching we return one value
$scope.getJobDepartmentImg = function() {
var jobDepartment = $scope.job.department;
for (var i in $scope.bgImages) {
var department = $scope.bgImages[i].departmentName;
var job_header = $scope.bgImages[i].s3ImageUrl;
if (jobDepartment === department) {
return job_header;
} else {
return default_job_header;
}
}
};
The loop is not terminated if condition is satisfiedd that method will continiouslyy can anyone help me?

put an second return outside else statement
$scope.getJobDepartmentImg = function() {
var jobDepartment = $scope.job.department;
for (var i in $scope.bgImages) {
var department = $scope.bgImages[i].departmentName;
var job_header = $scope.bgImages[i].s3ImageUrl;
if(jobDepartment === department){
return job_header;
}
}
return default_job_header;
}
it will iterate through array and return job_header if it finds one, or return default if loop ends

Related

The return false in jquery each loop not end the entire function

It seems that the return word in jquery each loop will not end the entire function. Here is the code below. The purpose is, when a value in the array is not a number, it should stop all the function, not only the loop. But it turns out that it will only stop the loop and contiue the other logic below.
In C# or Java, the return word will stop the entire function. Is not desgined like this in JavaScript?
function testMehtod() {
var itemIds = [];
$("#confirmOrderItemContainer").find(":checkbox:checked").each(function (i, o) {
itemIds[i] = $(o).attr('item-id');
if (isNaN(itemIds[i])) {
return false;
}
});
//other logic ...
}
if you need to catch breaking the loop and return false too:
function testMehtod() {
var itemIds = [];
var ret = true; // our flag variable with default value - everything is good
$("#confirmOrderItemContainer").find(":checkbox:checked").each(function (i, o) {
itemIds[i] = $(o).attr('item-id');
if (isNaN(itemIds[i])) { // not good
ret = false; // let set flag about it
return false; // break $.each loop
}
});
if (ret === false) { // not good? let's leave function
return false;
}
//other logic ...
}

Underscore reject Function with IndexOf removes all objects from array

I have a small Angular app that I'm writing that makes use of Underscore to look over each object in an array, and remove the object if it does not match the keyword (user input).
$scope.search = function() {
$scope.posts = _.reject($scope.posts, function(p) {
var i = 0;
if ($scope.keywords.indexOf(p.author) < 0 ) {
i++;
}
if ($scope.keywords.indexOf(p.id) < 0 ) {
i++;
}
if(i > 0) {
return true;
}
});
};
As you can see I'm setting a counter, and then adding to the counter if the keyword is found in the index, then at the end checking the counter to return true or false to remove the object from the array. $scope.posts is array of objects with my data and $scope.keywords is the user input. I'm wanting to lookup the input from $scope.posts.author object and $scope.posts.id object.
If I remove one of the if statements the function performs as expected: everything not matching the keyword is removed from the array. However, as soon as I add another if statement to the function (as seen in my example above), ALL objects are removed from the array.
It looks to me as though filter might be a better fit here:
$scope.posts = _.filter($scope.posts, function(p) {
return $scope.keywords.indexOf(p.author) > -1 || $scope.keywords.indexOf(p.id) > -1;
});
Working example: http://jsfiddle.net/4xp3sm10/
Instead of filter or reject it would be even easier to do it the opposite way using _.where
var newArray = _.where($scope.posts, {keyword : $scope.keyword});
There you go, one line.
Edit:
If you are stuck on doing it this way, here's a way you could clean it up a little.
$scope.posts = _.reject($scope.posts, function(p) {
var check = false;
if ($scope.keywords.indexOf(p.author) < 0 ) {
check = true;
}
if ($scope.keywords.indexOf(p.id) < 0 ) {
check = true;
}
if(i > 0) {
return check;
}
});
};
No need to use an integer like that
Since you are rejecting rows you will want to make sure ALL conditions are true. Your code is just checking for either one to be true.
$scope.search = function() {
$scope.posts = _.reject($scope.posts, function(p) {
return (
($scope.keywords.indexOf(p.author) < 0 ) &&
($scope.keywords.indexOf(p.id) < 0 )
);
});
};

Iterate a function until result from called function is equal, javascript

I need to iterate a function several times until it returns same thing twice.
This needs to go into a for-loop somehow but I can't get my head around how to this. Here's some code with 4 manual iterations. Any ideas how to put this in a for-loop?
Velocity.prototype.removeCombinedDistancesThatAreShorterThanTrainLength = function(wayPoints, lengthOfTrain){
var firstTry = this.removeWayPointsWhichAreShorterThenTrainLength(wayPoints, lengthOfTrain);
var secondTry = this.removeWayPointsWhichAreShorterThenTrainLength(firstTry, lengthOfTrain);
if(firstTry === secondTry){
return firstTry;
}else{
var thirdTry = this.removeWayPointsWhichAreShorterThenTrainLength(secondTry, lengthOfTrain);
if(thirdTry === secondTry){
return secondTry
}else{
var forthTry = this.removeWayPointsWhichAreShorterThenTrainLength(thirdTry, lengthOfTrain);
if(thirdTry === forthTry){
return forthTry
}
}
}
return forthTry;
};
Something like this (not tried, but should give you the general idea):
var lastTry = null;
var thisTry = wayPoints;
do
{
lastTry = thisTry;
thisTry = this.removeWayPointsWhichAreShorterThenTrainLength(lastTry, lengthOfTrain);
} while (lastTry !== thisTry);
If it's possible that the result will never become equal, consider implementing a safeguard for this, like a maximum number of iterations.

Check if an element exists in a object

I have a set of radio buttons, when a radio button is selected the element is pushed into an object.
Then I need to take the value of the elements in the object and then push them into an array, if they are not already in the array.
My problem is that I keep getting duplicates or more in my array of each of the values with this function because I am not checking correctly if they exists.
How can I check if the element already exists in my array and then exclude it from being added?
_this.selected = {};
_this.selectedArray = [];
//loop through the object
angular.forEach(_this.selected, function ( item ){
//if it is not the first time the array is getting data loop through the array
if(_this.selectedArray.length > 0) {
_this.selectedArray.forEach(function (node){
//check to see if the item already exists-- this is where it is failing
//and running the loop too many times
if(node.id !== item.id){
_this.selectedArray.push(item);
}
});
} else {
_this.selectedArray.push(share);
}
});
You can use additional hash to check if you have already added item to array.
_this.selected = {};
_this.selectedArray = [];
_this.selectedHash = {};
//loop through the object
angular.forEach(_this.selected, function ( item ){
if(_this.selectedHash[item.id]) { return; }
_this.selectedArray.push(item);
_this.selectedHash[item.id] = 1;
});
Have you tried jQuery's inArray? http://api.jquery.com/jquery.inarray
It works the same as the indexOf method on String.
You could try if $.inArray(node, selectedArray) == -1 // element is not in the array
You can run this function on that array to reduce it to unique values rather than applying complex code to check whether the array had an element or not
var getOnlyUniqueValuesInArray = function(arrayObj) {
return arrayObj.reduce(function(a, b) {
if (a.indexOf(b) < 0) a.push(b);
return p;
}, []);
};
Hi that should helps
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope){
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope) {
_this.selected = {};
_this.selectedArray = [];
//loop through the object
angular.forEach(_this.selected, function(item) {
//if it is not the first time the array is getting data loop through the array
if (_this.selectedArray.length > 0) {
var canAdd = true;
_this.selectedArray.forEach(function(node) {
//do not add iny any of node.id will be equal to item.id
if (node.id == item.id) {
canAdd = false;
}
});
if(canAdd){
_this.selectedArray.push(item);
};
} else {
_this.selectedArray.push(share);
}
});
})
});

Javascript conditional callbacks

I'm currently using javascript to do some experiments and although I'm not new to JS I have a doubt that I hope the good folks at SO will be able to help.
Basically I'm making a jsonp request to a webservice that returns me the amount/length on the reply (just counting objects).
Then I'm randomly selecting 9 of those objects to place in an array and here lies the problem. I would like to make sure that none of those 9 objects is repeated.
To achieve this I'm using the following code:
function randomizer() {
return Math.ceil(Math.random()*badges.length);
}
function dupsVerify(array, number) {
array.forEach(function () {
if(array === number) {
return true;
}
});
return false;
}
// Randomly choose 9 array indexes
var randomBadge = function () {
var selectedIndexes = new Array();
while(selectedIndexes.length < 9) {
var found = false;
var randomNumber = randomizer();
if(!dupsVerify(selectedIndexes, randomNumber)) {
selectedIndexes.push(randomNumber);
} else {
newRandom = randomizer();
dupsVerify(selectedIndexes, newRandom);
}
}
return selectedIndexes;
}
I've tried a couple different methods of doing this verification but I've been thinking if it wouldn't be possible to do the following:
Generate the random number and go through the array to verify if it already exists in the array. If it exists, generate another random number (randomize call) and verify again.. If it doesn't exist in the array, then push it to the "final" array.
How can I achieve this? Using callbacks?
Am I doing this right or should I chance the code? Is there a simpler way of doing this?
Best Regards,
This would get you the desired behavior:
function getRandomPositions(sourcearray, desiredcount){
var result = [];
while(result.lentgth < desiredcount){
var rnd = Math.ceil(Math.random()*sourcearray.length);
if (result.indexOf(rnd) == -1){
result.push(rnd);
}
}
return result;
}
Instead of generating X random numbers, just generate a random number, but don't add it if it already exists.
I ended up finding the best solution for this scenario by using the following code:
function randomizer() {
return Math.ceil(Math.random()*badges.length);
}
function dupsVerify(array, number) {
var result;
if(array.length === 0) {result = false;}
array.forEach(function (item) {
if(item === number) {
result = true;
} else {
result = false;
}
});
return result;
}
// Randomly choose 9 array indexes
function randomBadge() {
while(cards.length < 9) {
var randomNumber = randomizer();
if(!dupsVerify(cards, randomNumber)) {
cards.push(randomNumber);
} else {
randomBadge();
}
}
return cards;
}
This represents the same behavior (and a few minor code corrections) but ensures that I will never get an array with 2 repeated objects.

Categories

Resources