how to get all values in for loop angular js - javascript

when I alert this I only get the last value of id. ican't findout where I'm going wrong
$scope.addToList = function (products,qty) {
if ($scope.order.length > 0) {
for (var i = 0; i < $scope.order.length; i++) {
$scope.Thx=$scope.order[i].id;
}}};
alert($scope.Thx);

Declare the $scope.Thx as an array first.
$scope.Thx = [];
$scope.addToList = function (products, qty) {
if ($scope.order.length > 0) {
for (var i = 0; i < $scope.order.length; i++) {
$scope.Thx.push($scope.order[i].id);
}
}
};

This line will overwrite the $scope.Thx for each iteration inside the loop.
$scope.Thx=$scope.order[i].id;
Now there are two ways to get the desired result.
1. If you want the separate alert for each item in the array then:
$scope.addToList = function (products,qty) {
if ($scope.order.length > 0) {
for (var i = 0; i < $scope.order.length; i++) {
$scope.Thx=$scope.order[i].id;
alert($scope.Thx);
}}};
2. If you want single alert for all the items.
declare $scope.Thx as an array first.
$scope.Thx = [];
$scope.addToList = function (products, qty) {
if ($scope.order.length > 0) {
for (var i = 0; i < $scope.order.length; i++) {
$scope.Thx.push($scope.order[i].id);
}
}
};
var tempVar="";
for(var i=0; i<$scope.Thx.length;i++)
{
tempVar += $scope.Thx[0]+"\n";
}
alert(tempVar);

Related

How do I return a variable from nested For Loops in JavaScript without using a global variable?

Here is my code sans input
// Check if three addends equal sum and return the product if so
let result;
function addNumbers(first,second,third,sum) {
if (first + second + third === sum) {
result = first * second * third;
return (first * second * third);
}
};
// find three numbers in list that add up to specific number
function testResult(list,sum) {
let firstAddend;
let secondAddend;
let thirdAddend;
for (let i = 0; i < list.length; i++) {
firstAddend = list.shift();
for (let j = 0; j < list.length; j++) {
secondAddend = list[j];
for (let k = 1; k < list.length; k++) {
thirdAddend = list[k];
addNumbers(firstAddend,secondAddend,thirdAddend,sum);
}
}
}
};
What I want is testResult() to return the result from addNumbers() when it returns the product. I want to get rid of let result; and result = ... in addNumbers(). I've been confused about scope but I think I'm starting to understand. Does each for loop contain the scope of the previous? If anyone is interested this is from Advent of Code Day 1. I am not certain if having the data is necessary here. If it is let me know and I will edit accordingly.
Does each for loop contain the scope of the previous?
Yes, it does. Whenever you create a sub-scope, all the variables in the previous scope are available. So, you don't actually have to declare firstAddend and secondAddend and thirdAddend ahead of time:
function testResult(list,sum) {
for (let i = 0; i < list.length; i++) {
let firstAddend = list.shift();
for (let j = 0; j < list.length; j++) {
let secondAddend = list[j];
for (let k = 1; k < list.length; k++) {
let thirdAddend = list[k];
addNumbers(firstAddend,secondAddend,thirdAddend,sum);
}
}
}
}
Next, the return means that when you call the function, it takes on the value that you return. So, you don't need a global result variable, as you can just utilize the return value. However, you should move the if statement out of the addNumbers function and into the testResult function, as you need to know when to return, not just what to return. In fact, the addNumbers function is simply enough to where it should just go directly into testResult:
function testResult(list,sum) {
for (let i = 0; i < list.length; i++) {
let firstAddend = list.shift();
for (let j = 0; j < list.length; j++) {
let secondAddend = list[j];
for (let k = 1; k < list.length; k++) {
let thirdAddend = list[k];
if (firstAddend + secondAddend + thirdAddend === sum) {
return firstAddend * secondAddend * thirdAddend;
}
}
}
}
}
For practice, if you want the function, you could do something like the following:
function addNumbers(first,second,third,sum) {
if (first + second + third === sum) {
return (first * second * third);
} else {
return null; // return some value so the calling function knows that no sum was found
}
}
function testResult(list,sum) {
for (let i = 0; i < list.length; i++) {
let firstAddend = list.shift();
for (let j = 0; j < list.length; j++) {
let secondAddend = list[j];
for (let k = 1; k < list.length; k++) {
let thirdAddend = list[k];
let result = addNumbers(firstAddend, secondAddend, thirdAddend, sum);
if (result !== null) {
return result;
}
}
}
}
}

How can speed up search loop?

There is a cycle with the condition how can it be optimized so that the search is faster?
for (var i = 0; i < db.rows.length; i++) {
for (var j = 0; j < user.rows.length; j++) {
for (var k = 0; k < work.length; k++) {
if (db.rows[i].LOGIN === user.rows[j].login && work[k].name === db.rows[i].NAME) {
}
}
}
}
This is typically something that you would expect to see executed on the database.
That being said, you can split up the condition, so that you don't need to perform the second nested loop for every row:
for (var i = 0; i < db.rows.length; i++) {
for (var j = 0; j < user.rows.length; j++) {
if (db.rows[i].LOGIN === user.rows[j].login) {
for (var k = 0; k < work.length; k++) {
if (work[k].name === db.rows[i].NAME) {
}
}
}
}
}
You could take two Maps for the user logins and work names.
var userLogins = new Map(user.rows.map(o => [o.login, o])),
workNames = new Map(o => [o.name, o]),
for (var i = 0; i < db.rows.length; i++) {
if (userLogins.has(db.rows[i].LOGIN) && workNames.has(work[k].name)) {
// do something
}
}
If you need just the simple check with using the objects of user.rows or work, you could take a Set instead.
var userLogins = new Set(user.rows.map(({ login } => login)),
workNames = new Set(({ name }) => name),
for (var i = 0; i < db.rows.length; i++) {
if (userLogins.has(db.rows[i].LOGIN) && workNames.has(work[k].name)) {
// do something
}
}

javascript array - increment value at given key

I have a dynamic array and I am trying to increment the value by 1 if the key exists in the array. According to my debug it is incrementing the key and and creating a second key/value pair.
A snippet of my code:
for (var i = 0; i < choices.length; i++) {
console.log(choices[i]);
if (choices[i].YearTermId == 1) {
if (!lookup(firstChoice, choices[i].FirstChoiceOptionId)) {
firstChoice.push({
key: choices[i].FirstChoiceOptionId,
value: 1
});
} else {
firstChoice[choices[i].FirstChoiceOptionId] = firstChoice[choices[i].FirstChoiceOptionId] + 1;
}
more if/else..
function lookup( arr, name ) {
for(var i = 0, len = arr.length; i < len; i++) {
if( arr[ i ].key === name )
return true;
}
return false;
}
You're using an array where you should be using an object. If you use an object, your code can be rewritten as:
var firstChoice = {};
for (var i = 0; i < choices.length; i++) {
var firstChoiceOptionId = choices[i].FirstChoiceOptionId;
if (choices[i].YearTermId == 1) {
firstChoice[firstChoiceOptionId] = firstChoice[firstChoiceOptionId]
? firstChoice[firstChoiceOptionId] + 1
: 1;
/* ... */
}
}
If you need the data as an array afterwards, just map it:
var firstChoiceArray = Object.keys(firstChoice).map(function(key) {
return {
key: key,
value: firstChoice[key]
};
});
Conversely, if you have an input array and want to convert it to an object for manipulation, reduce it:
var firstChoice = firstChoiceArray.reduce(function(result, current) {
result[current.key] = current.value;
return result;
}, {});
I think you should increment value key, like:
firstChoice[choices[i].FirstChoiceOptionId].value ++;
And I would like to rewrite this code to:
var firstChoice = {};
for (var i = 0; i < choices.length; i++) {
if (choices[i].YearTermId == 1) {
if (!firstChoice[choices[i].FirstChoiceOptionId]) {
firstChoice[choices[i].FirstChoiceOptionId] = 0;
}
firstChoice[choices[i].FirstChoiceOptionId]++;
}
}
console.log(firstChoice);
Try with Array.map:
Example:
var a = [{key:"ab","value":1},{key:"cd","value":1},{key:"ef","value":1}];
a.map(function(item){if(item.key == this){item.value++}}, "cd");
So, a[1] will have value 2 after that.

How to rewrite loop to recursion

I implemented a search function and loop that search by collection. In first iteration I need to search by all collection, but all next iterations only by result of the first iteration. I use if-statement if (i >= 1) collection = result; to do it, but it's not safe because I need to save collection. Is it possible to rewrite loop to recursion function? How I can make it or make my code elegant?
var targets = target.split(' '); // => ['hello', 'world'];
for (var i = 0; i < targets.length; ++i) {
if (i >= 1) {
collection = result;
}
result = includes(collection, props, targets[i]);
}
My search function:
function includes(collection, props, target) {
var result = [];
var collection_length = collection.length;
var props_length = props.length;
var target_length = target.length;
for (var i = 0; i < collection_length; ++i) {
for (var j = 0; j < props_length; ++j) {
if (collection[i][props[j]]) {
if (collection[i][props[j]].toLowerCase().slice(0, target_length) === target) {
result.push(collection[i]);
continue;
}
}
}
}
return result.length !== 0 ? result : false;
}
var result = collection;
for (var i = 0; i < targets.length; ++i) {
result = includes(result, props, targets[i]);
}
Maybe I'm missing something but isn't this what you're trying to do?

removing duplicates from a nested/2D array (removing the nested duplicate element)

So that:
array = [[12,13,24],[24,22,11],[11,44,55]]
would return:
cleanedArray = [[12,13,24],[22,11],[44,55]]
I'm surprised not to have found this answered here.
var array = [[12,13,24],[24,22,11],[11,44,55]];
var output = [];
var found = {};
for (var i = 0; i < array.length; i++) {
output.push([]);
for (var j = 0; j < array[i].length; j++) {
if (!found[array[i][j]]) {
found[array[i][j]] = true;
output[i].push(array[i][j]);
}
}
}
console.log(output);
Are you looking for a function that does this for just two-dimensional arrays? If so, then I think this would work:
Array.prototype.clean = function()
{
var found = [];
for(var i = 0; i < this.length; i++)
{
for(var j = 0; j < this[i].length; j++)
{
if(found.indexOf(this[i][j]) != -1)
{
this[i].splice(j, 1);
}
else
{
found.push(this[i][j]);
}
}
}
return this;
};
If it's just a one-dimensional array you're looking for, then:
Array.prototype.clean = function()
{
var found = [];
for(var i = 0; i < this.length; i++)
{
if(found.indexOf(this[i]) != -1)
{
this.splice(i, 1);
}
else
{
found.push(this[i]);
}
}
return this;
};
this would work. If you're doing either of those, then do .clean() on your array to clean it up.
A simple function that modifies the original array is:
function removeDups(a) {
var item, j, found = {};
for (var i=0, iLen=a.length; i<iLen; i++) {
item = a[i];
j=item.length;
while (j--) {
found.hasOwnProperty(item[j])? item.splice(j,1) : found[item[j]] = '';
}
}
return a;
}

Categories

Resources