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])
Related
I am trying to create a JavaScript function that takes an array as a parameter and returns the first item in the array. This should work for an array of any size. Here is what I have so far, it appears to work just fine in the console but my instructor says there's a better way to do this:
var array = [];
function numbaOne(array) {
for (var i = 0; i < array.length; i++) {
console.log(array[0])
};
}
Any help would be appreciated. I've read about data structures and arrays but can't figure out how to simplify or make this better.
What you are doing is looping over the array and printing out the first item each time. You just want:
var array = [...];
function numbaOne(array) {
console.log(array[0]); // Print out the first value of the array
return array[0]; // Return the first value of the array
}
There is one edge case here. If the array is empty, then the function will fail because array[0] will be undefined.
So, a more complete version might be:
var array = [...];
function numbaOne(array) {
if(array.length > 0) { // Check if there is anything in the array
console.log(array[0]);
return array[0];
} else { // If there isn't, let's return something "bad"
console.log("The array is empty!");
return undefined;
}
}
var arr=[1,2,3,[4,5],6,[7,8,9]],x,j;
for(x in arr)
for(j in arr[x])
console.log(arr[x][j]);
I want to print 1,2,3,...,9 but the above code prints 4,5,7,8,9.
I think "join" is enough:
console.log(arr.join());
If i understand your question correctly, you want to console to log 1 through 9. The way you currently have it, its only going to print the arrays within your array - that is why you are only getting 4,5,7,8,9.
What you could do is check to see if the value is an array in your first loop - if it is, iterate over it and print the values. If it is not, simply print the value.
if(arr[x].constructor === Array) {
//loop over the array and print out the values
for (j in arr[x]) {
console.log(arr[x][j])
}
} else {
//print out the plain value
console.log(arr[x])
}
Here is a pen to show the result: http://codepen.io/kyledodge/pen/zGwPBo
Another option is to use recursion. You could do something like this:
var printArrayValue = function(array) {
for (var i = 0; i < array.length; i++) {
if (array[i].constructor === Array) {
//if this an array, call this function again with the value
printArrayValue(array[i]);
} else {
//print the value
console.log(array[i]);
}
}
}
printArrayValue(arr);
Here is a pen to show the result: http://codepen.io/kyledodge/pen/VLbrPX
Coerce each element to array:
var arr=[1,2,3,[4,5],6,[7,8,9]],x,j;
for(x in arr) {
var arr2 = [].concat(arr[x]);
^^^^^^^^^^^^^^^^^
for(j in arr2)
console.log(arr2[j]);
}
This works because concat takes either an array or a single value.
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 />");
This question already has answers here:
How to find the indexes of all occurrences of an element in array?
(16 answers)
Closed 8 years ago.
Say that I have an array containing strings:
var array = ["test","apple","orange","test","banana"];
and some strings are exactly the same (test). Say that I want to get all the indexes in the array where the string test is located in the array and not just the first indexOf. Is there a nice solution to this problem that is as fast as possible and not using jQuery, I.E getting 0,2 as a result?
Thanks
You can use the builtin Array.prototype.forEach like this
var indices = [];
array.forEach(function(currentItem, index) {
if (currentItem === "test") {
indices.push(index);
}
});
console.log(indices);
Even better you can use Array.prototype.reduce like this
var indices = array.reduce(function(result, currentItem, index) {
if (currentItem === "test") {
result.push(index);
}
return result;
}, []);
console.log(indices);
Since you want the solution to be even working in IE, you might want to go with the plain old loop, like this
var indices = [], i;
for (i = 0; i < array.length; i += 1) {
if (array[i] === "test") {
indices.push(i);
}
}
console.log(indices);
I have data that is in an array, these are the ID's for users that have commented on said post. I want to compare this array with the id of the user, and if their id is in this array, continue with the code.
my array looks like:
({0:"1", 3:"6"}) // 1 and 6 are the ID's that I want to work with.
So I want to do something like:
var array = ({0:"1", 3:"6"});
var userID = 6;
if(in(array)==userID)
{
///you are in the list, so do whatever
}
Instancing your array like that will not create an array, but an object. Normally, you instantiate arrays in javascript like this:
var arr = [17, 4711];
Checking for a value using Array.indexOf:
arr.indexOf(17); // => 0
arr.indexOf(4711); // => 1
arr.indexOf(42); // => -1
Pushing:
arr.push(42);
arr.indexOf(42); // => 2
Array.indexOf is not in IE < 9, so I suggest you look into using a shim.
function inArray(needle, haystack) {
var count = 0;
for (var k in haystack) {
if (haystack.hasOwnProperty(k)) {
++count;
}
}
for (var i in haystack) {
if(haystack[i] == needle) return true;
}
return false;
}
See : http://jsfiddle.net/ryN6U/1/
If will not work with your object :)
You can loop through your object and check it against your userid. Something like
$(document).ready(function(){
var myArray = ({0:"1", 3:"6"});
var userId = 6;
for(vals in myArray){
if(userId == myArray[vals]){
alert("userid exists in array");
}
}
});
When testing against an array I would use jQuery's inArray()
if your looking for the first item in an object with a certain value look at this thread
json index of property value