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;
}
}
Related
I have filter and map function chained. I need to do something conditional on whether a filter returns an empty array or not. However the map function on the array does not seem to be invoked if the filter returns an empty array.
const letters = ["a", "b", "c"];
const numbers = [1, 2, 3]
function result (arr) {
arr.filter((x) => {return x === "a"}).map((y, i, arr) => {
if(arr.length === 0) {
return //do something
} else {
return //do something else
}})
}
Is this expected or am I doing something wrong?
I was expecting the filter result to be passed to the map function, which can be used as the 3rd argument of the map function: map(item, index, array)
Here's a JSFiddle of the problem
https://jsfiddle.net/sub3z0xh/
You’re right about what’s happening. Array methods run once per element in the source array. If the source array is empty, it doesn’t run.
This isn’t new or working different with array methods vs a basic for loop. Example:
const arr = [];
for (let i = 0; i < arr.length; i++) {
console.log(“this code never runs because there are no elements to loop”);
}
So maybe just store the result of the filter in a variable instead. Get rid of the chained map since it may not run. Check the size/contents of your filtered array, then do stuff with that.
I am attempting to create a function that can take in an array and display its contents backwards. I am having trouble with understanding why my function call is showing undefined when I enter an array in its parameter.
var arrayOne = []
function printReverse(arrayOne) {
for(var i = arrayOne.length-1; i < 0; i--) {
console.log(arrayOne[i])
}
}
There is a misunderstading with your question:
What you want to achieve is console.log elements on screen, not return anything.
Your code
var arrayOne = []
function printReverse(arrayOne) {
for(var i = arrayOne.length-1; i < 0; i--) {
console.log(arrayOne[i])
}
}
Does not work because you have a wrong operator in your code at i < 0. This will return false at first iteration, because i will be arrayOne.length, which would be > 0 if there is any element on it.
Change this part to i >= 0 and your code will work and actually print the values on console.
However, if you really want to have a reverted array, then you should simply use Array reverse() instead of writing a function to return it.
so there are some fundamentals that are off there. as stated in another answer i will never be less than 0 because you are defining it as a value greater than 0 in your for loop. Give something like this a try
EDIT: the comments are correct in the sense that the array will be mutated so make a copy of the array first which I've added using the spread operator
Also as far as this returning undefined -- it should return undefined unless you comment out the return statement
const arrayOne = [];
function printReverse(array) {
if (!Array.isArray(array) && array.length === 0 ) {
return 'The array is empty';
}
const arrCopy = [...array];
// technically you could just reverse it
// if you return it you have to assign it to someone on the function call
// return arrCopy.reverse();
// if you want to log the reversed array you could also
// console.log(arrCopy.reverse());
// if you want to reverse it then log each single index
// arrCopy.reverse().forEach(function(item) {
// console.log(item);
// })
}
// if you were to just return the reversed array you would have to assign it to a variable
// this is just an example and wouldnt technically work because arrayOne is empty
// also if you use this YOU HAVE TO RETURN THE ARRAY COPY
// const reversedArray = printReverse(arrayOne);
If you want it to return something, you have to add a return within the function, such that
function printReverse(arrayOne) {
for(var i = arrayOne.length-1; i < 0; i--) {
console.log(arrayOne[i]);
}
return "";
}
However, in your case, this doesn't make a lot of sense. You can only return one thing, be it a String, int, array, object, whatever. But once your program hits one return statement, it will quit the function after returning the value.
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 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
I have an array of objects in javascript. I use jquery.
How do i get the first element in the array? I cant use the array index - as I assign each elements index when I am adding the objects to the array. So the indexes arent 0, 1, 2 etc.
Just need to get the first element of the array?
If you don't use sequentially numbered elements, you'll have to loop through until you hit the first one:
var firstIndex = 0;
while (firstIndex < myarray.length && myarray[firstIndex] === undefined) {
firstIndex++;
}
if (firstIndex < myarray.length) {
var firstElement = myarray[firstIndex];
} else {
// no elements.
}
or some equivalently silly construction. This gets you the first item's index, which you might or might not care about it.
If this is something you need to do often, you should keep a lookaside reference to the current first valid index, so this becomes an O(1) operation instead of O(n) every time. If you're frequently needing to iterate through a truly sparse array, consider another data structure, like keeping an object alongside it that back-maps ordinal results to indexes, or something that fits your data.
The filter method works with sparse arrays.
var first = array.filter(x => true)[0];
Have you considered:
function getFirstIndex(array){
var result;
if(array instanceof Array){
for(var i in array){
result = i;
break;
}
} else {
return null;
}
return result;
}
?
And as a way to get the last element in the array:
function getLastIndex(array){
var result;
if(array instanceof Array){
result = array.push("");
array.pop;
}
} else {
return null;
}
return result;
}
Neither of these uses jquery.
Object.keys(array)[0] returns the index (in String form) of the first element in the sparse array.
var array = [];
array[2] = true;
array[5] = undefined;
var keys = Object.keys(array); // => ["2", "5"]
var first = Number(keys[0]); // => 2
var last = Number(keys[keys.length - 1]); // => 5
I was also facing a similar problem and was surprised that no one has considered the following:
var testArray = [];
testArray [1245]= 31;
testArray[2045] = 45;
for(index in testArray){
console.log(index+','+testArray[index])
}
The above will produce
1245,31
2045,45
If needed you could exist after the first iteration if all that was required but generally we need to know where in the array to begin.
This is a proposal with ES5 method with Array#some.
The code gets the first nonsparse element and the index. The iteration stops immediately with returning true in the callback:
var a = [, , 22, 33],
value,
index;
a.some(function (v, i) {
value = v;
index = i;
return true;
});
console.log(index, value);
If you find yourself needing to do manipulation of arrays a lot, you might be interested in the Underscore library. It provides utility methods for manipulating arrays, for example compact:
var yourArray = [];
yourArray[10] = "foo";
var firstValue = _.compact(yourArray)[0];
However, it does sound like you are doing something strange when you are constructing your array. Perhaps Array.push would help you out?