Javascript indexOf method [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 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.

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

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

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.

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