I'm currently trying to make a search function that searches an array for a string and returns the index of the location in the array for which it matches the string.
Ex:
Array: [1,2,3,4,5,2,3,1,6,5,2]
Search input: 3
Output:
2
6
Search input: 2
Output:
1
5
10
Currently i have it outputting only 1 value by using
document.getElementById("result").innerHTML=
But I want it to return multiple results
If you write your own function, you should be able to return an array of indices:
function indicesOf(input, value) {
var indices = new Array();
for (var i = 0; i < input.length; i++) {
if (input[i] == value)
indices.push(i);
}
return indices;
}
Then you can combine the array values and put them into the result location, as suggested by #AnthonyGrist:
document.getElementById('result').innerHTML = indicesOf(input, value).join(', ');
I'm not sure if that's what you're after, but if you want to return all objects with a given selector from DOM (as opposed to acting on and returning filtered javascript array) then you could use document.querySelectorAll(<your_selector_here>) - more information at MDN here
You can do this
var arr = [1,2,3,4,5,2,3,1,6,5,2];
arr.map(function(x, i){
return x == 3 ? i : null;
}).filter(Number); // get indexes
The above maps and filters out the index. Then it is simply a matter of joining it
document.getElementById("result").innerHTML= arr.join("<br />");
Related
I know that the normal behavior of a for loop is similar to this:
for(let i = 0; i<5; i++){
console.log(i);
}
which gives me this result:
0
1
2
3
4
However the following code gives me a 5 as a result and I do not know why it doesn't give me a result similar to the example above.It doesn't behave as a for loop because it doesn't have into account the initializer. Thanks a lot for your help.
function charCount(str){
for(var i=2;i<=str.length;i++){
result = [i]
}
return result;
}
charCount('hello')
function charCount(str) {
result=[];
for(var i=2;i<=str.length;i++){
result.push(i);
}
return result;
}
charCount('hello')
When doing result=[i], you are just resetting whole array, push() appends i to the existing array in every iteration.
This code return "5" because
In your code you return last value of result
for example you pass string "hello" then for loop iterate 2 to 5(str.length) so in the last result variable has a value as 5 so when you return result valriable it return 5.
for returning all number 0 to 5 then modify your code
result.push(i)
so every time number store iin result list and in the last you return that list
You can also iterate through the count and push the values into a new array using the keys without .push() by referencing the key in a bracket within the for loop. By assigning the arrays key value with a bracket before you define the next value, you are ensuring that you are iterating through to a new key\value pair inside the array with each iteration up to the str length.
function charCount(str) {
result=[];
for(var i = 0; i < str.length; i++){
result[i] = i;
}
return result;
}
console.log(charCount('hello'))
Also consider the following code using a forEach loop where you can define your key/value pairs for parsing within the loop...
function charCount(str) {
result=[];
str = str.split(''); // split the string
str.forEach(function(value, index){
result[index] = value;
// or result[index] = index --> to push in the numbered values of the keys as values to the array --> [0,1,2,3,4];
})
return result;
}
console.log(charCount('hello'))
Frequency of a string in an array of strings
Create a function you are given a collection of strings and a list of queries. For every query there is a string given. We need to print the number of times the given string occurs in the collection of strings.
Examples:
Input :
a[] = [wer, tyu, uio]
b[] = [wer, wer, tyu, oio, tyu]
Output : [2 2 0]
Explanation :
a[0] appears two times in b[]
function occur (a,b) {
let count = [];
for (var i = 0; i<= a.length ; i++) {
for (var j = 0;j<= b.length; j++) {
if (a[i]==b[j]) {
return count[i] = count[i]++;
}
}
}
}
console.log(occur(["aaaa","cc" ,"dd"],["aaaa","dd"]));
You should use some form of hash to only iterate once through the collection of strings, before considering any of the queries. An ES6 Map can used for that purpose.
Then per entry in the hash you would have the frequency count (counted with reduce).
One idea would to not just return that hash, but return a function that consults the hash and returns the corresponding frequency or 0 if it is not in that hash.
Here is how that would look:
// Returns function that can answer queries for the given collection of strings
function freq(strings) {
const counts = strings.reduce((map, s) => map.set(s, (map.get(s)||0)+1), new Map);
return s => counts.get(s) || 0;
}
// Sample call. The 3 queries are fed into the function returned by freq
const results = ["wer", "tyu", "uio"].map(freq(["wer", "wer", "tyu", "oio", "tyu"]));
console.log(results);
This question already has answers here:
Filter strings in Array based on content (filter search value)
(6 answers)
Closed 6 years ago.
I have a array in javascript containing "aassd,v_value1,asadds,v_value2, asddasd...", and I need extract the values that begin with v_ in a new array.
I used the next function to get the values, but only get the first value.
function search (array,string) {
var arr= [];
for (var i=0; i<array.length; i++) {
if (array[i].match(string)){
arr.push(i)
return arr;
}
}
return -1;
}
search(array,'v_')
Thanks.
You should use .filter() method as below:
function search (array,string) {
return array.filter(function (val) {
return val.substr(0, string.length) === string;
});
}
The filter() method returns items of array which fulfills the condition in the callback function
I think below might work. Just string match and push to new array if found.
var arr = ['aassd','v_value1','asadds','v_value2','asddasd'];
var newArr = []
substring = "v_";
for (var i = 0; i < arr.length; i++) {
if (arr[i].search(substring) === 0) {
newArr.push(arr[i]);
}
}
alert(newArr);
function search (array,string) {
var arr= [];
for (var i=0; i<array.length; i++) {
//Do not use MATCH here as you need values that STARTS WITH "v_", match will give you values like this asdasdav_asdasda also.
if (array[i].startsWith(string)){
//instead of this
//arr.push(i)
//use this , the above will push the index, this will push the VALUE(as asked in the question)
arr.push(array[i])
//remove this: as this breaks on the first true condition , hence you get one value.
//return arr;
}
}
return arr;
}
The Mistakes
Do not use MATCH for it will return values with the pattern anywhere in the string.
Use startsWith instead
Return outside the loop as it ends the loop when it matches the first time and hence you get only the first item
You should push the value not the index as asked in the question. So do this arr.push(array[i])
Not sure how to explain this in words, but is there any function in javascript that, when given a string , will return the number of times it occurs in an array?
For example:
var arr = ["a","b","c","d","c","c","b"];
var repeats = arr.count("c");
With repeats then being equal to 3 as "c" occurs 3 times.
I tried to look this up but I wasn't sure on how to word it so I didn't get anything useful.
You can create your own function or add it to the prototype of Array:
Array.prototype.count = function (val){
var result = 0;
for(var i = 0; i < this.length; i++){
if(this[i] === val) result++;
}
return result;
}
Then you can do ['a','b', 'a'].count('a') // returns 2
You can use array.filter()
var arr = ["a","b","c","d","c","c","b"];
var repeats = arr.filter(function(value) { return value==="c"; } ).length;
console.log(repeats)
arr.filter(function(v){return v=='c';}).length
Exact Word Match Example
var search_word = 'me';
var arr = ['help','me','please'];
arr.filter(function(el){return el === search_word}).length;
The filter function will return the element if the result of the function is true. The function is called on each element of the array. In this case, we are comparing the array element to our search word. If they are equal (true) the element is returned. We end up with an array of all the matches. Using .length simply gives us the number of items in the resulting array; effectively, a count.
Partial Match Example
If you were to want something a little more robust, for instance count the number of words that contain the letter l, then you could tokenize the string and scan the index, or use some regex which is a little more costly, but also more robust:
var search_word = 'l';
var arr = ['help','me','please'];
arr.filter( function(el){ return ( el.match(search_word) || [] ).length }).length;
Note that match also returns an array of matching elements, but an unsuccessful match returns undefined and not an empty array, which would be preferred. We need an array to use .length (the inside one), otherwise it would result in an error, so we add in the || [] to satisfy the case when no matches are found.
Got a string that is a series of 0 or 1 bit and an array of values, if in the string are characters that are set to 1, I need to return the corresponding value from the array.
example: mystring = "0101"; myarray =["A","B","C","D"]; then result = "B,D"
how can I get this result?
for(var i=0;i<mystring.length;i++){
if(mystring[i] != 0)
{
result = myarray[i];
}
}
Your code seems to work just fine, so you can just add another array and push the values on to that:
var result = [];
for (var i = 0 ...
result.push(myarray[i]);
http://jsfiddle.net/ExplosionPIlls/syA2c/
A more clever way to do this would be to apply a filter to myarray that checks the corresponding mystring index.
myarray.filter(function (_, idx) {
return +mystring[idx];
})
http://jsfiddle.net/ExplosionPIlls/syA2c/1/
Iterate through the characters in the binary string, if you encounter a 1, add the value at the corresponding index in the array to a temporary array. Join the temporary array by commas to get the output string.
I am not really sure if this is what you are looking for, but this returns the array of matches.
var result = [];
for(var i=0;i<mystring.length;i++){
if(parseInt(mystring[i]) !== 0 ) {
result.push(myarray[i]);
}
}
return result;
result = new Array();
for(var i=0;i