accessing local variable outside of for loop - javascript

I have a function
$rootScope.getCurrency = function() {
for (var i = 0; i < data.records.length; i++) {
for (var j = 0; j < data.records[i].columns.length; j++
if (data.records[i].columns[j].fieldname == "Currency") {
// Here I want to
// return the values
// if I do something like
return data.records[i].columns[j].value
// the loop exits on the first condition
// and does not iterate over completely. If I put
// return outside of the
// for loops it says i, j are undefined.
// How can I use the value outside of this loop
}
}
}
}
}
I have to use the returned value in my HTML for binding data.
My HTMl looks like:
ng-repeat i in someArray ng-if={{i.type==currency?getCurrency():''}}

Try pushing the values to an array:
$rootScope.getCurrency = function() {
var result = [];
for (var i = 0; i < data.records.length; i++) {
for (var j = 0; j < data.records[i].columns.length; j++
if (data.records[i].columns[j].fieldname == "Currency") {
// Add to array
result.push(data.records[i].columns[j].value);
}
}
}
return result;
}

Related

Not being able to reference a variable from outside the loop

Iam not able to reference a variable from outside the loop in the following function. I want to use the value inside the function itself but the scope doesnt seem to allow it.
function coinOnTheTable(m, k, board) {
for (var i = 0; i < board.length; i++) {
for (var j = 0; j < m; j++) {
if (board[i][j] === "*") {
const a = `${i}${j}`;
return a;
}
}
}
}
Works, While
function coinOnTheTable(m, k, board) {
for (var i = 0; i < board.length; i++) {
for (var j = 0; j < m; j++) {
if (board[i][j] === "*") {
const a = `${i}${j}`;
}
}
}
return a;
}
gives an error
return a;
^
ReferenceError: a is not defined
That's because a variable defined as const or let has "block scope". That means it is only visible inside the nearest set of curly braces. So:
function foo() {
const foo = 'foo-string';
if(1) {
const bar = 'bar-string';
console.log(bar); // This is fine
}
console.log(foo); // This is also fine
console.log(bar); // Error!
}
To solve your problem, you need to define your variable outside of the block defined by the nested for loop. So:
function coinOnTheTable(m, k, board) {
let a;
for(var i = 0; i < board.length; i++){
for(var j = 0; j < m; j++){
if(board[i][j] === "*"){
a = `${i}${j}`;
}
}
}
return a;
}
Note, the reason it changes from const to let is because const variables cannot be reassigned, but since you want to declare it as undefined (at the start of the function, then assign a string to it (inside the loop), you need to be able to reassign it.
make a function scope:
function coinOnTheTable(m, k, board) {
let a;
for(var i=0;i<board.length;i++){
for(var j=0;j<m;j++){
if(board[i][j]==="*"){
const a=`${i}${j}`;
}
}
}
return a;
}

Make javascript variable can be empty

Hi i have this function below that removes duplicates from the variable suggest but sometimes the data i receive for the suggest variable is empty and the code below wont work beacause of the JSON.parse function how do i make it so that the variable accepts empty data so that the code below will still run without any problems. Any help would be appreciated thanks!
function suggestData(data){
var suggest = []; // I tried adding this and setting it to null but it doesn't seem to work.
suggest = JSON.parse(data);
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
You can set suggest inside an if condition to check whether data exists or not
function suggestData(data){
var suggest = [];
if(data){
suggest = JSON.parse(data);
}
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
Also you can simply end the function if you do not want to execute it when data is empty:
function suggestData(data) {
if(!data){
return false;
}
//other code here
...
}
Set the length conditionally as,
var length = suggest? suggest.length: 0;
function suggestData(data){
var suggest = [];
suggest = JSON.parse(data);
var length = suggest? suggest.length: 0;
for (var i = length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
}
suggestData(null);
function suggestData(data){
var suggest = []; // I tried adding this and setting it to null but it doesn't seem to work.
if(data)
suggest = JSON.parse(data);
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
Just add the if condition on parsing line like
written in above code::
if(data)
suggest = JSON.parse(data);
The simplest:
if(!data || !suggest)
return;
let array = [1,2,3,8,3,4,4,5]
const removeDuplicateItems = arr => [...new Set(arr)];
console.log(removeDuplicateItems(array))
If you just want to remove duplicated items in an array, you can instead try Set which is quite handy
Even if array is empty or null, this method removeDuplicateItems will still works

Create and initialize bidimensional array in javascript

I am trying to create and initialize a bidimensional array in javascript inside an AngularJS application as follows:
$scope.invalidVote = [];
for (var i = 0; i < $scope.arry1.length; i += 1) {
$scope.answersCount[i] = $scope.arry1[i].arry2.length;
for(var j = 0; j < $scope.arry1[i].arry2.length; j += 1) {
$scope.invalidVote[i][j] = false;
}
}
But it doesn't work, What is the right way to do that?
try this:
$scope.invalidVote = [];
for (var i = 0; i < $scope.arry1.length; i++) {
$scope.answersCount[i] = $scope.arry1[i].arry2.length;
$scope.invalidVote[i] = [];
for(var j = 0; j < $scope.arry1[i].arry2.length; j++) {
$scope.invalidVote[i][j] = false;
}
}
I'm assuming $scope.arry1[i] is an array that contain other arrays and is already fill with values.
So your code should look like:
$scope.invalidVote = $scope.arry1;
for (var i = 0; i < $scope.arry1.length; i += 1)
{
$scope.answersCount[i] = $scope.arry1[i].length;
for(var j = 0; j < $scope.arry1[i].length; j += 1)
{
$scope.invalidVote[i][j] = false;
}
}
'$scope.invalidVote = $scope.arry1;' declaring "invalidVote" like this ensure it contains the same amount of indexes.

how not to get out of array boundaries

I have an array and by looping I compare cell with a cell near it. I get the 'out of range' exception,
How can I fix it ?
for (var i = 0; i < array.length ; i++) {
if ((++array[i] == array[i+1])) {
alert("yes");
}
else {
alert("no");
}
}
Run your loop from for (var i=0; i<array.length -1; i++) instead (because you compare against array[i+1])
Just try with:
for (var i = 0; i < array.length - 1; i++) {}
Not sure what you had in mind but using ++ outside of a for loop is never a good idea as it can be confusing. Use another variable to point to another item in the array while looping together with a bounds checker is easier to debug and keeps loop simple.
//displays 01010
//1=2(0),2=2(1),2=4(0),4=4(1),4=5(0)
var ptr = 0;
var items = new Array (1, 2, 2, 4, 4, 5);
for (var i = 0; i < items.length; i++) {
ptr++
if(ptr >= items.length)break;
if (items[i] == items[ptr]) {
console.log(1);
}
else {
console.log(0);
}
}
//or
//displays 10001 as each value is increased then compared
//2=2(1),3=2(0),3=4(0),5=4(0),5=5(1)
ptr = 0;
for (var i = 0; i < items.length; i++) {
ptr++
if (ptr >= items.length) break;
if (++items[i] == items[ptr]) {
console.log(1);
}
else {
console.log(0);
}
}

Compare two arrays in javascript

I'd like to check which elements are equal in my two arrays, but can't get it working.
This is my code:
for (var i; i < bombs.length; i++) {
for (var j; j < bombsDb.length; j++) {
if (bombs[i].name === bombsDb[j].address) {
console.log(bombs[i].name);
} else {
console.log("non-equal elements");
}
}
}
So the first array contains objects from the google places api and the second one contains data from my database.
Thanks in advance!
You have to initialize i and j;
for (var i = 0; i < bombs.length; i++) {
for (var j = 0; j < bombsDb.length; j++) {
if (bombs[i].name === bombsDb[j].address) {
console.log(bombs[i].name);
} else {
console.log("non-equal elements");
}
}
}
Comparing can also be done using the .not selector from jquery. Check this:
var a = [1,2,3,4,5,6];
var b = [4,5,6,7,8,9];
$(a).not( $(a).not(b).get() ).get();
This will return the following array
[4,5,6]
You are missing the initial assignment to i and j in your for loop.
// here
// v
for (var i = 0; i < bombs.length; i++) {
// your loop
}
This causes the comparision to return false in the first iteration of the loop since undefined < bombs.length always return false, so it will not proceed.

Categories