How to retrieve the first item in an array in javascript? - javascript

I am new to javascript. I am doing a task which trying to get the first item removed from an array in javascript.
Method One
function getFirst(arr, item) {
arr.push(item);
var removed = arr.shift();
return removed;
}
Method Two
function getFirst2(arr, item) {
arr = arr.push(item);
var removed = arr.shift();
return removed;
}
I comes out with these two solution but only method one accepted and method two is the wrong one which return Uncaught TypeError: arr.shift is not a function().
What is the extacly meaning of Uncaught TypeError and state that arr.shift is not a function but it works on Method one?
Any help will be appreciate! Thanks!

Your function getFirst2() is not working because of arr = arr.push(item).
Here arr actually becomes a number, as the push method on an array returns the new length property of the object upon which the method was called.
Thus calling method push on a number throws a TypeError.

Your first Method is alright. But i'd like to note that you do not always have to create a local fucntion-scope variables. Your return statement can return computed values. So instead of
function getFirst(arr, item) {
arr.push(item);
var removed = arr.shift();
return removed;
}
I would go for
function getFirst(arr, item) {
arr.push(item);
return arr.shift();
}

You can apply the shift function on an array. In method 2, arr is not an array anymore because I think that the push method returns the length of the array. This is why you are getting a typeError.
Try printing arr before applying the shift method to see what it is.

Javascript has many inbuilt functions that are attached to different data types. The Array type has the functions push(), unshift(), shift() etc that are attached to every array but not to other non-array types.
When you use these Array functions on any type that is not an array you get the Uncaught type error, because the Javascript interpreter cannot read the function off that type.
Your second function on this line: arr = arr.push(item); , changes the value of arr to a number because the return value of the function arr.push(item); is a number(Int). Hence trying to call .shift() on arr is no longer allowed because arr is no longer an array.

Related

How can I access an array value without using array[key]?

I'm writing a simple code to get the value inside an array. I'm using array[key] to get the value stored inside this array, in a for loop.
var array = ["Foo", "Bar"];
function getValue() {
for (var key = 0; key < array.length; key++) {
console.log(array[value]);
}
}
This method is simple and works fine, however, I've read that this could cause security issue (The Dangers of Square Bracket Notation), and ESlint is not OK with it, throwing this error:
Generic Object Injection Sink (security/detect-object-injection)
Detects variable[key] as a left- or right-hand assignment operand. (ESLint reference)
How can I access the value of the array without using this method ?
I've already read the related question: Why is it bad pratice calling an array index with a variable? and as this question seems too hard to generalize I decided to ask a new canonical question.
There are a couple of ways to do this.
First: You could use for..of loop. for..of doesn't use the square bracket notation and doesn't give the index directly.
for (let element of list) {
console.log(element);
}
Second: The other way is what #Rajesh has mentioned: ForEach.
list.ForEach((element) => {
console.log(element)
});
JavaScript offers many method to help you iterate over array for mapping, filtering and only iterating arrays. Look on the few of them:
forEach() method
let arr = [1,2,3,4,10];
arr.forEach((item, index) => console.log(item)) //1,2,3,4,10
This method also allows you to get index of the item.
for-of loop
for(item of arr) {
console.log(item) //1,2,3,4,10
}
This new feature introduced in ES6 and this recommended to iterate over arrays.
If you want manipulate arrays you can use following method, which also iterating over arrays:
filter()
arr.filter((item, index)=> item > 5) // Return new array [10]
map()
arr.map((item, index)=> item*2) // Return new array [2,4,6,8,20]
Use Array.prototype.at.
['a','b','c','d','e'].at(2); // 'c'

JQuery - pushing elements to an array

I have the following working code:
var eachLine;
var newArray =[];
$.each(eachLine, function(){
allWordsArray.push($.trim(this));
});
But when I try to modify the above the above code like below: I am passing the variable to a function which returns a variable.
var eachLine;
var newArray =[];
$.each(eachLine, function(){
var stem = stemmer($.trim(this));
allWordsArray.push(stem);
});
It is throwing me a type error later in some other function - saying not an object while passing an object.
Could some one please point out what I am doing wrong here. Thanks in advance.
$.each() : A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1.
eachLine is not an object, $.each requires an object or array to iterate which return index,key,value in callback function.

Javascript: Adding a property to an array of objects

I have an array of objects as follows:
var myarray=[{"name":"John","address":"home"},{"name":"Peter","address":"home"}]
and I would like to run a function to add a property to the array as follows:
[{"name":"John","address":"home","collection":"friend"},
{"name":"Peter","address":"home","collection":"friend"}]
I have tried doing this:
myarray=myarray.map(function (err, myarray){
myarray.collection="friend";
return myarray;
}
console.log(myarray)
But the console continues to return this:
[{0},{1}]
Can anyone help me? Thank you
Your code is not adding the property to the contents of the array. The values of the array are given as the first parameter to the callback function (the second parameter is an index, and not the array itself—that's the third parameter). Simply assign the new property to the first parameter of the callback function, rather than the second one.
Edit - As #zerkms points out, however, if you're looking to update the current array rather than generate a new array, map is probably not best solution here. forEach provides a method for iterating over the current array, and modifying each of its values (which is what you're doing). This would looks omething like this:
myarray.forEach(function(value) {
value.collection = "friend";
});
As you'll notice in the documentation for .map, the callback function returns the new value that will appear in the new array that is generated by map; if you're changing the current array in place (i.e. by modifying the properties of its contents), there's no need to return anything.
myarray.map(function(value) {
value.collection = "friend";
});
Also note that both map and forEach are methods, so you need to close the method invocation with ).
Wrong use of map().
The first argument of map() is the current element of the array, the second argument is it's index.
For example:
['a','b','c'].map(function(element, index){console.log(element, index)});
Will result in
a 1
b 2
c 3
So inside your function myarray was your index, and you were trying to add the property to the index.
Now you have to options. Either you use the map() as it's ment to be used and assign it's return value to myarray:
myarray = myarray.map(function(element) {
element.collection = "friend";
return element;
});
or you can, because objects are not getting copied but referenced when passed as an argument, not care about the return values and modify the elements directly:
myarray.map(function(element) {
element.collection = "friend";
}); // returns [undefined, undefined ...]
This, however, isn't the way one should use map()
Better: Use forEach()
myarray.forEach(function(element) {
element.collection = "friend";
});
Hope it helped.
Greets!
All you have to do is changing the reference object within map function
myarray.map(function (value){
value.collection = "friend";
});
console.log(myarray);

Javascript array type casting

I've found something interesting and I don't know why it's happening.
If I try in google chrome developer tools, the following two staments
(Array([1,2,3])).filter(function (item, index, array) {
return item === 1;
}); ==> []
and
([1,2,3]).filter(function (item, index, array) {
return item === 1;
}); ==> [1]
The results are an empty array for the first statement and array with a single value (1) for the second
Inspecting the parameters for the callback function, i found that in the first statement the arguments are (array, index, value) and for the second statemente are(value, index, array).
Inspecting with typeof and constructor of both objects the result are the expected, and the same "object", and Array.
Why is this happening?
Thanks
Because that's not how you define an array with Array().
Should be without the square brackets, otherwise it's an array of a single element, which is also an array ([1,2,3]).
Array(1,2,3)
That inner array never equals to 1 (basically you check [1,2,3] == 1), so the result is an empty array.
If you define an array by using Array([1,2,3]) this code, then the following array will be created,
[[1,2,3]]
Since you are pushing an array into another one. And if you really want the Array function to create an array by reading an array then you have to write something like this,
Array.apply([], [1,2,3])
But the above one is completely pointless. Again I am telling it is completely pointless since we are having an array that we require in our hand. But just for a knowledge you can know about it.
Array([1,2,3]) create array of arrays [[1, 2, 3]] so .map()function will iterate one time only.
If you want to create array with Array constructor use next syntax:
Array(1,2,3)
the shorter is the better :
[1,2,3].filter(item => item === 1);

get element from arbitrary list in javascript

i have a function in javascript where i need to retrieve the last element of the list. the list can be an array, string, list in numbers (not array). I tried converting the list into a String and then an array and retrieving it by index, but that's not working.
Here is the code I tried:
function last(list){
var array = new String(list);
array = array.split("");
return array[array.length-1];
}
I don't understand what the problem is because test suite says Expected: 5 instead got: 5
I am using code wars and did not write the tests. Is it expecting a Number and getting a String '5' ? I don't understand types in loosely typed languages very well yet.
from the comments, I think you mean you want to either return the last element in an array, the last character in a string, or the last argument passed if multiple arguments were passed. This would do it:
function last() {
if (arguments.length > 1) { // first we handle the case of multiple arguments
return Array.prototype.pop.call(arguments);
}
value = arguments[0]
if (typeof value === 'string') { // next, let's handle strings
return value.split('').pop();
}
if (Object.prototype.toString.call( [] ) === '[object Array]') {// Arrays are of type object in js, so we need to do a weird check
return value.pop();
}
}
arguments is a pseudo-array that contains all arguments passed into the function, so for last(1,2,3,4,5), arguments would be roughly [1,2,3,4,5]. It's not exactly that though, because arguments has all args in order and a length property, but it's prototype isn't Array, so it isn't truly [1,2,3,4,5] and lacks all of array's functions. This is why we need to call pop in the context of arguments (in javascript, Function.prototype.call calls the function passing the first arguments as the value of this, and all the rest of the arguments into the arguments pseudo-array, so for example last.call([], 1, 2, 3) would call last in the context of a new array and with arguments roughly equal to [1,2,3]).
the rest of the code is pretty straightforward, except for the check to see if value is an array, which is further explained here.
Finally, pop is an array method that removes the last element from an array and returns it.

Categories

Resources