Js array length increase too early [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a condition based array length. my problem is the array is not increase at the right time.
its hard to explain so i made a plunker and sample code:
When i click on push the second time i want the alert to be 'gt 1'.
How i can solve this problem? maybe with counter or something?
<div ng-repeat="user in data">
<a ng-click="pushUser(user)">push</a>
</div>
app.controller('MainCtrl', function($scope) {
$scope.users = [];
$scope.data = [{name: 1} ,{name: 2}, {name:3}];
$scope.pushUser = function(user) {
if($scope.users.length > 1) {
alert('gt 1');
$scope.users.push(user);
} else {
alert('lt 1');
$scope.users.push(user);
}
}
});
http://plnkr.co/edit/FsjV20MI0bcwKMqOUOoS?p=preview

Since the initial length of array users is 0, the condition if($scope.users.length > 1) will be evaluated to false, when you click first time. Hence the else part will end up adding an element in the user array.
For the second time, when you click the link, the condition if($scope.users.length > 1) will still be evaluated to false as the length of array is equal to 1 and not >1. So the else part will still get executed and will result in increasing length of user array to 2.
Subsequent clicks, will result in displaying alert as gt 1. Hence to achieve the desired result, you should change the condition to if($scope.users.length >= 1). Note the operator has been changed to indicate if the array length is greater or equal to one, which is true when you click the link second time.

Push and then check:
$scope.users.push(user);
if($scope.users.length => 1) {
alert('gt 1');
} else {
alert('lt 1');
}

Related

How does the following code work step by step? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I came across this piece of code which checks if number of occurrences of an element in an array is greater than it is specified, and if yes it will remove the number:
function deleteNth(arr,x) {
var cache = {};
return arr.filter(function(n) {
cache[n] = (cache[n]||0) + 1;
return cache[n] <= x;
});
}
But I didn't understand the code from here: arr.filter(function(n){cache[n] = (cache[n]||0) + 1;return cache[n] <= x;});
Can anyone please explain in simple words what happens here and how does cache[n] part work.
Why is cache[n] incremented?
Thanks!
The arr.filter() begins by iterating over each item in the array and this case each item is represented by 'n'.
This item is then added to the empty object where 'n' is the key and the value is then incremented by one for each new item added to the object.
The return statement uses the cache to do a check of what 'n' values are less than or equal to x. If it returns false they are not added into the new array that is created. So if 'x' is 3 it will remove everything after the first three items from the array.
EDIT
Another way of writing the function which might make it more clear could be
function deleteNth(arr,x) {
return arr.filter((item, index) => {
if (index <= x) {
return item;
}
});
}

Puppeteer check through website content/elements [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I need to check through the elements of the website for my code, but I can't understand how to do it with puppeteer on Node.JS
Here's the code I tried:
if(page.content('input[data-kwimpalaid="1580983806648-1"]'))
found = true
if(found = true)
console.log("I found it")
if(found = false)
console.log("I didn't found it")
So what I need basically, I have a website with element ID's ending in 1 to 20, and it can be random, and consecutive. For example it may start at 1, then has 6 ids (1,2,3,4,5,6) or it can start at 5 (5,6,7,8,9,10). I want to check for every ID, and if it exists then change the value of ''found'' to true. If the page doesn't have id 1, try id 2, id 3, id 4, etc.. until it finds an input with that ID/CLASS that exists on that website.
Shortly, I need to check if the selector element I use exists on the website or not (content).
Hm, what about this? On top of my head!
let found = false;
const allInputs = page.content('input[data-kwimpalaid]'); // Assuming an Array of elements here
for (let i = 1; i < 6; i++) {
if (allInputs.find((input) => input.dataset.kwimpalaid.startsWith(i))) {
found = true;
break;
}
}
if (found) {
console.log("I found it");
} else {
console.log("I didn't found it")
}
So basically scan the document once for all elements with an ID.
Then look at each element individually.
The for-loop respects your preference.
If an element is found Array.prototype.find will return it. Otherwise, its return value is undefined.
I'm assuming here, that puppeteer behaves similar to DOM in browser. Someone else might correct me, if that isn't the case.

better way to find duplicate item in a sequence than checking its first and last index [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm solving a challenge which has a sequence of integers from 1 to N, and the task is to find the missing integer in the sequence, and the one integer that is duplicated.
The constraints -
You are not allowed to sort the array.
Your solution should not time out for large values of N.
Ideally, your solution should not use extra space except the one provided by the input array (which can be modified).
My current code times out, I'm assuming that's because the complexity for finding the duplicate element might be O(N^2).
For the missing element, my algorithm is -
Create a variable, set it to 1, and loop until condition is true
In loop, check if variable is present in array, if so, increment variable and continue loop
If variable was not found in array, this was the missing element. Break out of loop.
This should run in O(N) time, so this part should be fine.
For the duplicate element, my approach was to check the first index and last index of every element in array. For unique elements, the index values would be the same, but it would be different for the duplicates.
This is where the problem lies, I think.
My code -
function solution(array) {
var missing = 0,
duplicate = 0;
let notFound = true;
let curr = 1;
while (notFound) {
if (array.indexOf(curr) === -1) {
notFound = false;
break;
}
curr++;
}
missing = curr;
duplicate = array.find((e, i, arr) => arr.indexOf(e) !== arr.lastIndexOf(e));
return [missing, duplicate];
}
console.log(solution([2, 3, 1, 4, 4, 6]));
I checked some related questions, like this and this, but couldn't get anything out of them.
How do I fix this?
I think you can hash your input array.
What I mean by that is, suppose your array is [4,1,5,6,3,1]
Here is a simple pseudo-code.
You can get duplicate element like this:
for i:array.length
array[array[i]] = array[i]*-1 // you found and marked first element of your array
if(array[i] > 0) //it would be positive if you found and marked an element twice.
array[array[i]] is the duplicate element
This runs in O(n)
Now to get the missing element, you can traverse the array again
for i:array.length
if (array[i] > 0 && array[i]!=duplicate element) //there would be two positive numbers, missing number and the duplicate
i = missing element
This O(n) again, so its O(n) overall.
If anything is unclear, you can ask. Sorry about preferring to write a pseudo-code instead of an explanation.

What is the best way to find the first occurrence of an item in a collection and update it [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a collection in Javascript/Typescript
[
{"order":1,"step":"abc:","status":true},
{"order":2,"step":"xyz","status":true},
{"order":3,"step":"dec","status":false},
{"order":4,"step":"pqr","status":false},
{"order":5,"step":"tuv","status":false}
....
];
I need to write a function that every time its called it identifies the first occurrence of a false (Order:3 in the above example) and updates it to true. If the above method is called again now the next element (order:4 ) would have been updated. The steps that are false will always be below steps that are completed i.e true.
What's the best way (simplest, less code and elegant) to write this function? I can manually loop through using for each of the items in the collection, check for the first occurrence of false and then update it.
In ES6 you can use this:
yourArray.find((element) => !element.status).status = true;
See find() and its compatibility table.
And note that this will fail if there is no entry with status: false. A quick and dirty fix could for example look like the one below. But that entirely depends on your use case.
(yourArray.find((element) => !element.status) || {}).status = true;
Pretty much what you described is how you would do it:
for (let order of orders) {
if (!order.status) {
order.status = true;
break;
}
}
When you look for the matching occurance you require, then insert a 'break' statement to stop the search.
Example:
for( var i=0; i<recs.length; i++ ) {
if ( recs[i]['status'] == false ) {
recs[i]['status'] = true;
break;
}
}
You can use Lodash find method to find the first occurence of false status.
Sample Code
_.find(users, function(object) { return object.status === false });
lodash find documentation link

Regex in JavaScript for first SUM/MIN/MAX/AVG found in string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
What I'm trying to do is the following:
SUM(Sales) + SUM(Revenue)
or MIN(Sales) + SUM(Revenue).
What I want is the first calculation. So for 1), the result "SUM" will be given, and for 2) the result "MIN" will be given.
I've tried this for if statements but it's either impossible, or incredibly difficult to do that way. Could anyone guide me on potentially a RegEx way of doing this?
What I tried in if statements:
function hasFormula(formulaToLower) {
// formulaToLower could equal "SUM(Sales) + SUM(Revenue)" etc
// could also equal "SUM(Sales) + MIN(Revenue)" - this will return MIN, but it return SUM.
if (formulaToLower.indexOf('sum') !== -1) {
return "SUM";
}
if (formulaToLower.indexOf('min') !== -1) {
return "MIN";
}
}
Obviously though, this will bring out MIN first, even if it's found second, and so on...
You can use a regexp that allows all the combinations you want. The matches will be returned in the correct order if you use the global modifier, or only the first one will be returned if you do not:
var matcher = /SUM|MIN|MAX|AVG/;
var str1 = 'SUM(Sales) + SUM(Revenue)';
var str2 = 'MIN(Sales) + SUM(Revenue)';
console.log(str1.match(matcher)[0]) // SUM
console.log(str2.match(matcher)[0]) // MIN
*The [0] part takes the first element in the array of results returned by match.

Categories

Resources