IndexOf() he will only show the first encounter with the letter [duplicate] - javascript

For example, if I had "scissors" in variable and wanted to know the position of all occurrences of the letter "s", it should print out 1, 4, 5, 8.
How can I do this in JavaScript in most efficient way? I don't think looping through the whole is terribly efficient

A simple loop works well:
var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "s") indices.push(i);
}
Now, you indicate that you want 1,4,5,8. This will give you 0, 3, 4, 7 since indexes are zero-based. So you could add one:
if (str[i] === "s") indices.push(i+1);
and now it will give you your expected result.
A fiddle can be see here.
I don't think looping through the whole is terribly efficient
As far as performance goes, I don't think this is something that you need to be gravely worried about until you start hitting problems.
Here is a jsPerf test comparing various answers. In Safari 5.1, the IndexOf performs the best. In Chrome 19, the for loop is the fastest.

Using the native String.prototype.indexOf method to most efficiently find each offset.
function locations(substring,string){
var a=[],i=-1;
while((i=string.indexOf(substring,i+1)) >= 0) a.push(i);
return a;
}
console.log(locations("s","scissors"));
//-> [0, 3, 4, 7]
This is a micro-optimization, however. For a simple and terse loop that will be fast enough:
// Produces the indices in reverse order; throw on a .reverse() if you want
for (var a=[],i=str.length;i--;) if (str[i]=="s") a.push(i);
In fact, a native loop is faster on chrome that using indexOf!

When i benchmarked everything it seemed like regular expressions performed the best, so i came up with this
function indexesOf(string, regex) {
var match,
indexes = {};
regex = new RegExp(regex);
while (match = regex.exec(string)) {
if (!indexes[match[0]]) indexes[match[0]] = [];
indexes[match[0]].push(match.index);
}
return indexes;
}
you can do this
indexesOf('ssssss', /s/g);
which would return
{s: [0,1,2,3,4,5]}
i needed a very fast way to match multiple characters against large amounts of text so for example you could do this
indexesOf('dddddssssss', /s|d/g);
and you would get this
{d:[0,1,2,3,4], s:[5,6,7,8,9,10]}
this way you can get all the indexes of your matches in one go

function charPos(str, char) {
return str
.split("")
.map(function (c, i) { if (c == char) return i; })
.filter(function (v) { return v >= 0; });
}
charPos("scissors", "s"); // [0, 3, 4, 7]
Note that JavaScript counts from 0. Add +1 to i, if you must.

In modern browsers matchAll do the job :
const string = "scissors";
const matches = [...string.matchAll(/s/g)];
You can get the values in several ways. For example :
const indexes = matches.map(match => match.index);

More functional fun, and also more general: This finds the starting indexes of a substring of any length in a string
const length = (x) => x.length
const sum = (a, b) => a+b
const indexesOf = (substr) => ({
in: (str) => (
str
.split(substr)
.slice(0, -1)
.map(length)
.map((_, i, lengths) => (
lengths
.slice(0, i+1)
.reduce(sum, i*substr.length)
))
)
});
console.log(indexesOf('s').in('scissors')); // [0,3,4,7]
console.log(indexesOf('and').in('a and b and c')); // [2,8]

indices = (c, s) => s
.split('')
.reduce((a, e, i) => e === c ? a.concat(i) : a, []);
indices('?', 'a?g??'); // [1, 3, 4]

Here is a short solution using a function expression (with ES6 arrow functions). The function accepts a string and the character to find as parameters. It splits the string into an array of characters and uses a reduce function to accumulate and return the matching indices as an array.
const findIndices = (str, char) =>
str.split('').reduce((indices, letter, index) => {
letter === char && indices.push(index);
return indices;
}, [])
Testing:
findIndices("Hello There!", "e");
// → [1, 8, 10]
findIndices("Looking for new letters!", "o");
// → [1, 2, 9]
Here is a compact (one-line) version:
const findIndices = (str, char) => str.split('').reduce( (indices, letter, index) => { letter === char && indices.push(index); return indices }, [] );

using while loop
let indices = [];
let array = "scissors".split('');
let element = 's';
let idx = array.indexOf(element);
while (idx !== -1) {
indices.push(idx+1);
idx = array.indexOf(element, idx + 1);
}
console.log(indices);

Another alternative could be using flatMap.
var getIndices = (s, t) => {
return [...s].flatMap((char, i) => (char === t ? i + 1 : []));
};
console.log(getIndices('scissors', 's'));
console.log(getIndices('kaios', '0'));

I loved the question and thought to write my answer by using the reduce() method defined on arrays.
function getIndices(text, delimiter='.') {
let indices = [];
let combined;
text.split(delimiter)
.slice(0, -1)
.reduce((a, b) => {
if(a == '') {
combined = a + b;
} else {
combined = a + delimiter + b;
}
indices.push(combined.length);
return combined; // Uncommenting this will lead to syntactical errors
}, '');
return indices;
}
let indices = getIndices(`Ab+Cd+Pk+Djb+Nice+One`, '+');
let indices2 = getIndices(`Program.can.be.done.in.2.ways`); // Here default delimiter will be taken as `.`
console.log(indices); // [ 2, 5, 8, 12, 17 ]
console.log(indices2); // [ 7, 11, 14, 19, 22, 24 ]
// To get output as expected (comma separated)
console.log(`${indices}`); // 2,5,8,12,17
console.log(`${indices2}`); // 7,11,14,19,22,24

Just for further solution, here is my solution:
you can find character's indexes which exist in a string:
findIndex(str, char) {
const strLength = str.length;
const indexes = [];
let newStr = str;
while (newStr && newStr.indexOf(char) > -1) {
indexes.push(newStr.indexOf(char) + strLength- newStr.length);
newStr = newStr.substring(newStr.indexOf(char) + 1);
}
return indexes;
}
findIndex('scissors', 's'); // [0, 3, 4, 7]
findIndex('Find "s" in this sentence', 's'); // [6, 15, 17]

function countClaps(str) {
const re = new RegExp(/C/g);
// matching the pattern
const count = str.match(re).length;
return count;
}
//countClaps();
console.log(countClaps("CCClaClClap!Clap!ClClClap!"));

Using recursion function:
let indcies=[];
function findAllIndecies(str,substr,indexToStart=0) {
if (indexToStart<str.length) {
var index= str.indexOf(substr,indexToStart)
indcies.push(index)
findAllIndecies(str,substr,index+1)
}
}
findAllIndecies("scissors","s")

You could probably use the match() function of javascript as well. You can create a regular expression and then pass it as a parameter to the match().
stringName.match(/s/g);
This should return you an array of all the occurrence of the the letter 's'.

Related

JavaScript Trying to Print The Number of Times a Letter Appears In String But It Prints More than Once

In the code below, I am trying to check how many times a letter in a string appears. Problem with the code below is that it prints each letter more than once. It needs to collect all the same letters and show the number of times it occurs in the string and display it once.
const string = 'mississippi'
const letters = [...string]
let currentLetter = ''
let letterOccurance = []
for(let i = 0; i < letters.length; i++){
let letterFrequency = letters.filter((letter)=>{
return letter === letters[i]
})
letterOccurance.push([`${letters[i]}`,letterFrequency.length])
}
console.log(letterOccurance)
That's too much code just to get the number of times a letter appears in a string. Try the following code:
const string = 'mississippi';
let frequency = {};
for (let letter of string) {
if (frequency[letter]) {
frequency[letter]++;
} else {
frequency[letter] = 1;
}
}
console.log(frequency);
You're always pushing the letter to the array, whether it already exists there or not:
letterOccurance.push([`${letters[i]}`,letterFrequency.length])
You could check if it exists first:
if (!letterOccurance.find(l => l[0] === letters[i])) {
letterOccurance.push([`${letters[i]}`,letterFrequency.length])
}
Or even skip it entirely if you've already seen it, since the first time you find any letter you already know its complete count:
for(let i = 0; i < letters.length; i++){
if (letterOccurance.find(l => l[0] === letters[i])) {
continue;
}
// the rest of the loop...
}
There's honestly a variety of ways you could step back and re-approach the problem. But for the question about why letters are repeating, that's simply because each iteration of the loop unconditionally appends the letter to the resulting array.
How about writing a more generic item-counting function and then layering countLetters as a simple partial application of the identity function?
const countBy = (fn) => ([...xs]) =>
xs .reduce ((a, x) => {const k = fn (x); a [k] = (a[k] || 0) + 1; return a}, {})
const countLetters = countBy (x => x)
console .log (countLetters ('missisippi'))
countBy is fairly generic. You pass it a function to convert your values to strings, and pass your array of items to the function it returns. Strings are array-like enough that this just works for our simple countLetters. But we could use it for other counts as well, such as:
countBy (x => x .grade) ([{id: 1, grade: 'A'}, {id: 2, grade: 'B'}, {id: 3, grade: 'A'}])
//=> {"A": 2, "B": 1}
Here's a solution using a Set to get the individual letters and String.split() to count.
const countChars = str => Object.fromEntries(
[...new Set(str)]
.map(c => [c, str.split(c).length-1])
)
console.log(countChars('mississippi'));
Using reduce to build the object
const countChars = str => [...str].reduce(
(a, c) => (a[c] ? a[c]++ : a[c]=1, a),
{}
)
console.log(countChars('mississippi'));
var result =

Calculating second largest number in array (Javascript) : Seems to work in Sandbox but fails Hackerrank testing

Tried to determine the second largest number in an array (Javascript) on CodeSandbox. It seems to work fine, but it fails the CodeWars testing. I have added a dummy array just to run my own tests in Sandbox.(Have mercy, I'm a beginner and this is my first StackOverFlow question)
const nums = [3, 100.3, 88, 1, -2.4, 9, 18];
const getSecondLargest = (nums) => {
const descending = nums.sort((a, b) => b - a);
return descending[1];
};
console.log(getSecondLargest(nums)); // console returns 88
EDIT: Okay so I with my super-tired brain I said CodeWars, when I actually meant Hackerrank (so sorry!). I realized they didn't necessarily test with NaNs, but they did have repeating numbers, so using the index of [1] isn't ideal. The exercise is from the 10 Days of Javascript - Day 3: Arrays https://hackerrank.com/domains/tutorials/10-days-of-javascript
So I now tried this code below, and it passes...but my code seems a bit janky, is there a cleaner way to write this, and can I combine it with the isNan logic then?
const nums = [3, 100, 88, 100, -2.4, 9, 18];
const getSecondLargest = (nums) => {
const ascending = nums.sort((a, b) => a - b);
if (ascending[ascending.length - 2] === ascending[ascending.length - 1]) {
return ascending[ascending.length - 3];
} else {
return ascending[ascending.length - 2];
}
};
console.log(getSecondLargest(nums)); // console returns 88
It looks like there maybe strings in the array and you need to handle that. Here are a few ways:
One is to filter the non-numerical stuff out before sorting. You can use isNaN() to test if an object "is not a number".
const getSecondLargest = (nums) => {
const descending = nums
.filter(n => !isNaN(n))
.sort((a, b) => b - a);
return descending.length < 2 ? undefined : descending[1];
};
Another option is to handle the strings in sorting. Push them to the end of the array:
const getSecondLargest = (nums) => {
const descending = nums.sort((a, b) => {
if (isNaN(a) && isNaN(b)) return 0;
if (isNaN(a)) return 1;
if (isNaN(b)) return -1;
return b - a;
});
return descending.length < 2 || isNaN(descending[1]) ? undefined : descending[1];
};
A third way is a simple for loop that keeps track of the 2 highest values:
const getSecondLargest = (nums) => {
let max1 = undefined;
let max2 = undefined;
for (let n of nums) {
if (isNaN(n)) continue;
if (max2 === undefined || n > max2) {
if (max1 === undefined || n > max1 ) {
max2 = max1;
max1 = n;
}
else {
max2 = n;
}
}
}
return max2;
}

Optimize Time Complexity For Odd Occurrences In Array

I have this code that pairs same elements in an array, with the expectation that the array will have an odd length and it should return the only element that couldn't get a pair. So I wrote the code just well, and it works fine for smaller arrays, but with very large big integers of over 1 billion, the time complexity became O(N**2) and then the need to refactor my code to get a much better performance for large arrays and large array elements. Here is my code below;
function solution(A) {
if(!Array.isArray(A)) return 0;
var temp = new Array(A.length);
var position = 0;
for(let i=0; i<A.length; i++){
if(temp.includes(A[i])){
position = temp.indexOf(A[i]);
index = A.indexOf(A[i]);
delete temp[position];
delete A[index];
delete A[i];
}else{
temp[i] = A[i];
}
}
for(let j=0; j<A.length; j++){
if(A[j] !== undefined) return A[j];
else continue;
}
}
To test it, source data can look like [2,3,6,7,3,5,5,6,2] and it will give an output of 7. But when the array is so large up to [1,2,....] with length n = n=999,999, or n = 5000,000,000, the time complexity increases exponentially.
You might use Object to store non-paired elements only.
Please note that you don't need to store all the array elements and their counts in the Object and then filter by count (like #StepUp does).
Everything's been done in a single loop.
The function returns Array of all non-paired elements:
const solution = A => Array.isArray(A) ?
Object.keys(
A.reduce((r, k) => {
r[k] = r[k] || 0;
if (++r[k] > 1) delete r[k];
return r;
}, {})
) : [];
console.log(solution([2, 3, 6, 7, 3, 5, 5, 6, 2]))
We can try to find odd occurrences for one iteration by using great features of object. Object is key - value pair. So access to object key is O(1). So when we meet the same element, then we just increment value:
const hashMap = arr.reduce((a, c)=> {
a[c] = a[c] || 0;
a[c] += 1;
return a;
},{})
const result = Object.keys(hashMap).filter(key => hashMap[key] === 1);
An example:
let arr = [2, 3, 6, 7, 3, 5, 5, 6, 2];
const hashMap = arr.reduce((a, c)=> {
a[c] = a[c] || 0;
a[c] += 1;
return a;
},{})
const result = Object.keys(hashMap).filter(key => hashMap[key] === 1);
console.log(result);
My two 100% JavaScript solutions with optimized time complexity. The first one is using Set:
function solution(A) {
const pairs = new Set();
for (const num of A) {
if (pairs.has(num)) {
pairs.delete(num);
} else {
pairs.add(num);
}
}
const [unpaired] = pairs;
return unpaired;
}
The second one is using bitwise XOR:
function solution(A) {
let unpaired;
for (const num of A) {
unpaired ^= num;
}
return unpaired;
}

Split String Every 2 Character into Array

I have a problem with my code. I have a series of string. For example I made this:
var a = 12345678
I want to split these string into an array, so that it will produce something like this:
[12,23,34,45,56,67,78]
I already tried this code:
var newNum = a.toString().match(/.{1,2}/g)
and it returns this result instead of the result I wanted
[12,34,56,78]
Are there any solution to this? Thanks in advance.
Shortest way:
'abcdefg'.split(/(..)/g).filter(s => s);
// Array(4) [ "ab", "cd", "ef", "g" ]
Explanation: split(/(..)/g) splits the string every two characters (kinda), from what I understand the captured group of any two characters (..) acts as a lookahead here (for reasons unbeknownst to me; if anyone has an explanation, contribution to this answer is welcome). This results in Array(7) [ "", "ab", "", "cd", "", "ef", "g" ] so all that's left to do is weed out the empty substrings with filter(s => s).
Hope this helps.
var a = 12345678;
a= a.toString();
var arr=[];
for (var i =0; i<a.length-1; i++) {
arr.push(Number(a[i]+''+a[i+1]));
}
console.log(arr);
You could use Array.from() like this:
let str = "12345678",
length = str.length - 1,
output = Array.from({ length }, (_,i) => +str.slice(i, i+2))
console.log(output)
Here's a generic solution for getting varying size of chunks:
function getChunks(number, size) {
let str = number.toString(),
length = str.length - size + 1;
return Array.from({ length }, (_,i) => +str.slice(i, i + size))
}
console.log(getChunks(12345, 3))
console.log(getChunks(12345678, 2))
We can do this using Array.reduce :
Firstly, convert the number into a string and then split it into an array
Secondly, apply reduce on the resulting array, then append current element ele with the next element only if the next element exists.
Lastly, after the append is done with the current and next element convert it back to a number by prefixing it with an arithmetic operator + and then add it to the accumulator array.
var a = 12345678;
const result = a.toString().split("").reduce((acc, ele, idx, arr) => {
return arr[idx + 1] ? acc.concat(+(ele + arr[idx + 1])) : acc;
}, []);
console.log(result);
console.assert(result, [12,23,34,45,56,67,78]);
Another approach, using reduce
var a = 12345678
a.toString()
.split('')
.reduce((c,x,i,A)=>i>0?c.concat([A[i-1]+A[i]]):c,[])
The pattern is start with the first two digits (12) and then add eleven until you have an array that ends with the last digit of the input string (8).
let str = `12345678`;
const eleven = string => {
let result = [];
let singles = string.split('');
let first = Number(singles.splice(0, 2).join(''));
for (let i = 0; i < string.length-1; i++) {
let next = 11 * i;
result.push(first+next);
}
return result;
}
console.log(eleven(str));
var a = 12345678;
console.log(
String(a)
.split("")
.map((value, index, array) => [value, array[index + 1]].join(''))
.map(item => Number(item))
);
output - [ 12, 23, 34, 45, 56, 67, 78, 8 ]
explanation
String(a) - convert your number value 'a' into string, to prepare for operations
split("") - convert string value into array
.map((value, index, array) => [value, array[index + 1]] ...
for every item from array, take current value and next value, and put them into array cell
.join('')) - then create string from this array value like this [ '1', '2' ] => ['12']
.map(item => Number(item)) - at the end, convert every array item into number.
You could use a recursive approach. Here I used an auxiliary function to perform the recursion, and the main function to convert the number to a string.
See example below:
const arr = 12345678;
const group = a => group_aux(`${a}`);
const group_aux = ([f, s, ...r]) =>
!s ? [] : [+(f+s), ...group_aux([s, ...r])];
console.log(group(arr));
My requirement is to convert a MD5 string (with length: 32) to a Uint8Array (with length: 16) as the key of AES algorithm. Reference from the post above, thanks.
var a = 'a12ab32fd78a89efa12ab32fd78a89ef';
var arr=[];
for (var i =0; i<a.length-1; i+=2) {
arr.push(parseInt(a[i]+''+a[i+1], 16));
}
console.log(arr.length);
console.log(arr);
console.log(new Uint8Array(arr));
If order doesn't matter, a more legible solution is:
let even = '12345678'.match(/(..)/g)
let odd = '2345678'.match(/(..)/g)
let result = [...even, ...odd]
If order does matter, just use .sort():
result.sort()

Finding all indexes of a specified character within a string

For example, if I had "scissors" in variable and wanted to know the position of all occurrences of the letter "s", it should print out 1, 4, 5, 8.
How can I do this in JavaScript in most efficient way? I don't think looping through the whole is terribly efficient
A simple loop works well:
var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "s") indices.push(i);
}
Now, you indicate that you want 1,4,5,8. This will give you 0, 3, 4, 7 since indexes are zero-based. So you could add one:
if (str[i] === "s") indices.push(i+1);
and now it will give you your expected result.
A fiddle can be see here.
I don't think looping through the whole is terribly efficient
As far as performance goes, I don't think this is something that you need to be gravely worried about until you start hitting problems.
Here is a jsPerf test comparing various answers. In Safari 5.1, the IndexOf performs the best. In Chrome 19, the for loop is the fastest.
Using the native String.prototype.indexOf method to most efficiently find each offset.
function locations(substring,string){
var a=[],i=-1;
while((i=string.indexOf(substring,i+1)) >= 0) a.push(i);
return a;
}
console.log(locations("s","scissors"));
//-> [0, 3, 4, 7]
This is a micro-optimization, however. For a simple and terse loop that will be fast enough:
// Produces the indices in reverse order; throw on a .reverse() if you want
for (var a=[],i=str.length;i--;) if (str[i]=="s") a.push(i);
In fact, a native loop is faster on chrome that using indexOf!
When i benchmarked everything it seemed like regular expressions performed the best, so i came up with this
function indexesOf(string, regex) {
var match,
indexes = {};
regex = new RegExp(regex);
while (match = regex.exec(string)) {
if (!indexes[match[0]]) indexes[match[0]] = [];
indexes[match[0]].push(match.index);
}
return indexes;
}
you can do this
indexesOf('ssssss', /s/g);
which would return
{s: [0,1,2,3,4,5]}
i needed a very fast way to match multiple characters against large amounts of text so for example you could do this
indexesOf('dddddssssss', /s|d/g);
and you would get this
{d:[0,1,2,3,4], s:[5,6,7,8,9,10]}
this way you can get all the indexes of your matches in one go
function charPos(str, char) {
return str
.split("")
.map(function (c, i) { if (c == char) return i; })
.filter(function (v) { return v >= 0; });
}
charPos("scissors", "s"); // [0, 3, 4, 7]
Note that JavaScript counts from 0. Add +1 to i, if you must.
In modern browsers matchAll do the job :
const string = "scissors";
const matches = [...string.matchAll(/s/g)];
You can get the values in several ways. For example :
const indexes = matches.map(match => match.index);
More functional fun, and also more general: This finds the starting indexes of a substring of any length in a string
const length = (x) => x.length
const sum = (a, b) => a+b
const indexesOf = (substr) => ({
in: (str) => (
str
.split(substr)
.slice(0, -1)
.map(length)
.map((_, i, lengths) => (
lengths
.slice(0, i+1)
.reduce(sum, i*substr.length)
))
)
});
console.log(indexesOf('s').in('scissors')); // [0,3,4,7]
console.log(indexesOf('and').in('a and b and c')); // [2,8]
indices = (c, s) => s
.split('')
.reduce((a, e, i) => e === c ? a.concat(i) : a, []);
indices('?', 'a?g??'); // [1, 3, 4]
Here is a short solution using a function expression (with ES6 arrow functions). The function accepts a string and the character to find as parameters. It splits the string into an array of characters and uses a reduce function to accumulate and return the matching indices as an array.
const findIndices = (str, char) =>
str.split('').reduce((indices, letter, index) => {
letter === char && indices.push(index);
return indices;
}, [])
Testing:
findIndices("Hello There!", "e");
// → [1, 8, 10]
findIndices("Looking for new letters!", "o");
// → [1, 2, 9]
Here is a compact (one-line) version:
const findIndices = (str, char) => str.split('').reduce( (indices, letter, index) => { letter === char && indices.push(index); return indices }, [] );
using while loop
let indices = [];
let array = "scissors".split('');
let element = 's';
let idx = array.indexOf(element);
while (idx !== -1) {
indices.push(idx+1);
idx = array.indexOf(element, idx + 1);
}
console.log(indices);
Another alternative could be using flatMap.
var getIndices = (s, t) => {
return [...s].flatMap((char, i) => (char === t ? i + 1 : []));
};
console.log(getIndices('scissors', 's'));
console.log(getIndices('kaios', '0'));
I loved the question and thought to write my answer by using the reduce() method defined on arrays.
function getIndices(text, delimiter='.') {
let indices = [];
let combined;
text.split(delimiter)
.slice(0, -1)
.reduce((a, b) => {
if(a == '') {
combined = a + b;
} else {
combined = a + delimiter + b;
}
indices.push(combined.length);
return combined; // Uncommenting this will lead to syntactical errors
}, '');
return indices;
}
let indices = getIndices(`Ab+Cd+Pk+Djb+Nice+One`, '+');
let indices2 = getIndices(`Program.can.be.done.in.2.ways`); // Here default delimiter will be taken as `.`
console.log(indices); // [ 2, 5, 8, 12, 17 ]
console.log(indices2); // [ 7, 11, 14, 19, 22, 24 ]
// To get output as expected (comma separated)
console.log(`${indices}`); // 2,5,8,12,17
console.log(`${indices2}`); // 7,11,14,19,22,24
Just for further solution, here is my solution:
you can find character's indexes which exist in a string:
findIndex(str, char) {
const strLength = str.length;
const indexes = [];
let newStr = str;
while (newStr && newStr.indexOf(char) > -1) {
indexes.push(newStr.indexOf(char) + strLength- newStr.length);
newStr = newStr.substring(newStr.indexOf(char) + 1);
}
return indexes;
}
findIndex('scissors', 's'); // [0, 3, 4, 7]
findIndex('Find "s" in this sentence', 's'); // [6, 15, 17]
function countClaps(str) {
const re = new RegExp(/C/g);
// matching the pattern
const count = str.match(re).length;
return count;
}
//countClaps();
console.log(countClaps("CCClaClClap!Clap!ClClClap!"));
Using recursion function:
let indcies=[];
function findAllIndecies(str,substr,indexToStart=0) {
if (indexToStart<str.length) {
var index= str.indexOf(substr,indexToStart)
indcies.push(index)
findAllIndecies(str,substr,index+1)
}
}
findAllIndecies("scissors","s")
You could probably use the match() function of javascript as well. You can create a regular expression and then pass it as a parameter to the match().
stringName.match(/s/g);
This should return you an array of all the occurrence of the the letter 's'.

Categories