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

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;
}
});
}

Related

Does one push everytime creates array inside of array? [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 2 days ago.
Improve this question
I created button that is generate a random number every time , but in the console log it shows it like this:
small project i have been working on during course of javascript
I tried to make one array of random numbers and when it reach above 4 random numbers i will use Shift method to erase one. ( I also tried to use for loop )
What actually happen that is it kind of creates me new array inside of the orginal array
let randomArr = [];
if (randomArr.length >= 4) {
randomArr.shift();
lastNumbers.textContent -= randomArr + ",";
return randomArr;
} else {
randomArr.push(randomNumber);
// randomArr.length = randomArr;
lastNumbers.textContent += randomArr + ",";
// return randomArr;
}
Ty for helping!

Why does Douglas Crockford write `if` conditionals that are executed everytime except the first? [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 7 years ago.
Improve this question
I've been reading his book and he does stuff like this is a lot. For example, on p. 48 of JavaScript: The Good Parts, he has the function
Cat.prototype.purr = function ( n )
var i, s = '';
for ( i = 0; i < n; i += 1 )
{
if (s) {
s += '-';
}
s += 'r';
}
return s;
}
where the if conditional if essentially useless since it returns true every time but the first. The function could be written equivalently
Cat.prototype.purr = function ( n )
var i, s = 'r';
for ( i = 2; i < n; i += 1 )
{
s += '-r';
}
return s;
}
for better performance. Also, why does he define i outside the for loop?
The two functions are not the same. The original function returns an empty string of n is 0. Your function returns "r" if n is 0;
I am guessing that this is just an example to illustrate a common need where you want to separate a list of items with a character like '-' or ','.
You might write a loop like this and instead of 'r' you would have the names of items. E.g. "Bob-Mike-Jill-Jack"
To simplify the example for the book then he has just used 'r' which means the code could be written a different way like you say. But for a generic list you do want to add the separator every time except the first.
In regards to the var placement if you are declaring s then it is less chars to declare i there as well rather than write out var again in the loop. But I suspect it is probably just his idea of good practice to declare all variables that you use at the start of the function.

Javascript indexOf method [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 7 years ago.
Improve this question
I recently came across this little problem to solve on a website, counting the number of vowels in a string. I succeeded using a switch statement, but when I looked at the authors solution they had used the following function.
function vowel_count(str1) {
var vowel_list = 'aeiouAEIOU';
var vcount = 0;
for (var x = 0; x < str1.length ; x++) {
if (vowel_list.indexOf(str1[x]) !== -1) {
vcount += 1;
}
}
return vcount;
}
alert(vowel_count("The quick brown fox"));
Can anyone please explain what exactly is happening in the if statement,
I can see the index of whatever string that is passed to the function is being used but why would the statement == or !== -1. I'm a bit confused as to how the function is checking the string.
Thanks in advance.
The indexOf() function returns the index of an element we're looking for in a given array. However, if the element is nowhere to be found in the array, indexOf() returns -1 instead.
So in your case:
if (vowel_list.indexOf(str1[x]) !== -1) {
means something like "if the current letter can be found in my list of vowels".
Does that make sense ?
The indexOf method returns the position of the first occurrence of a specified value in a string. It returns -1 if the value to search for never occurs.
JavaScript, like most programming languages, starts counting from 0.
"foo".indexOf('f'); is 0.
The function returns -1 if the value isn't found.

Js array length increase too early [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 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');
}

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