Query regarding arrays - javascript

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.

Related

Why does this for loop in Javascript give me a number instead of the list of numbers from 0 to 4?

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'))

Search and extract string in javascript array [duplicate]

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])

JavaScript function that takes an array as a parameter

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

forEach works - why not for loop?

I'm working on the flatten kata at codewars.com - my code closely resembles a solution I've found, so I feel like my logic is on the right track. But I can't seem to get my code to work and I don't know if it's a dumb syntax error or if I'm doing something fundamentally incorrect.
Instructions:
Write a function that flattens an Array of Array objects into a flat Array. Your function
must only do one level of flattening.
flatten([[1,2,3],["a","b","c"],[1,2,3]]) // => [1,2,3,"a","b","c",1,2,3]
Working solution using forEach:
var flatten = function (lol){
var res = [];
lol.forEach(function (x) {
if (x instanceof Array)
res = res.concat(x);
else
res.push(x);
});
return res;
}
My code using for loops:
var flatten = function (array){
var newArray = [];
for (i = 0; i < array.length; i++) {
if (i instanceof Array)
for (e = 0; e < i.length; e++) {
newArray.push(e);
}
else
newArray.push(i);
}
return newArray;
}
The most important reason why it isn't working is that you are treating your indices (i and e) as if they were the actual array elements (hence, the sub Arrays themselves). i is not the actual array, and does not have any array properties. It is just a number.
Each element must be referenced via the array[index], so in the case of the array argument, in the top loop, you would check array[i], but most importantly, if it is not an array, that is what you would push().
In your inner loop, you face a similar issue with e. However, you cannot simply do array[e] as the array you would be looking at would be array[i]. The proper way to address this is to make another variable for the array OR simply array[i][e]. Again, this is the value you would push().
I understand that this answer is a little vague, but it is intentionally so, as this is obviously an assignment from which you are trying to learn.
You need to use the value of the original array to push/concat into the new one. Also, you don't need to check the type, you can just concat everything:
var flatten = function (array) {
var newArray = [];
var arrayLength = array.length;
for (i = 0; i < arrayLength; i++) {
newArray = newArray.concat(array[i]);
}
return newArray;
}
if (array[i] instanceof Array)
Your algorithm looks fine, but you are referencing a Number index where you mean to be referencing an array element. Fix this in 3 places and your code should work.
Spoiler:
var flatten = function (array){
var newArray = [];
for (i = 0; i < array.length; i++) {
if (array[i] instanceof Array)
newArray = newArray.concat(array[i]);
else
newArray.push(array[i]);
}
return newArray;
}

jQuery/Javascript if value is in array, continue

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

Categories