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);
Related
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.
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.
I am passing an array of objects to a function whose role is to remove some of those objects according to some sort of criterium.
The problem is that the scope isn't being handled the way I would like it to be, and the original array is not being updated.
In that function, the return value is already used and may not be changed. How might I be able to change the array?
A variable pointing to an array is a reference to it. When you pass an array, you're copying this reference. So you should just modify the array parameter and it will modify the original array.
var a=[1,2,3];
var c=f(a);
alert(a); // a is now [1,2,3,6]
function f(b) {
b.push(6);
return 1;
}
I am writing a Javascript function to count the number of instances of an element in an unsorted array. It has a method signature like this
Array.prototype.numberOfOccurrences = function() {
}
Here is an example of expected behavior
var arr = [4, 0, 4];
Test.assertEquals(arr.numberOfOccurrences(4), 2);
My problem is that I don't know how to access the elements in the array. The function doesn't take any parameters so how do I reference the array being passed in?
Note: The instructions aren't very descriptive for this kata on code wars and adding a parameter to the function returns some error unexpected token.
Inside the function you are creating into the Array.prototype you can access all the prototype functions through the "this" keyword.
Meaning you can access the array items using numeric properties like this[0] or this[1] to a access the first and second item respectively.
You can also call functions which allows you to iterate over each item on the array, such as: forEach, filter, etc.
Please refer this page to see everything you can do with the array prototype:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype
Lastly don't forget that the JavaScript implementation varies on each browser, so a function that works on Chrome, might not work on InternetExplorer, always confirm on caniuse.com If the function you are used has the same implementation on your targets browsers.
Cheers.
Whether you should extend javascript base objects aside, this is your friend:
Array.prototype.numberOfOccurrences = function(valueToFind) {
return this.filter(function(item) {
return item === valueToFind;
}).length;
}
var a = [1,2,3,3,3,3];
console.log(a.numberOfOccurrences(3)); //4
As noted above, if you're not able to change the function signature for whatever reason you can specify it as follows:
Array.prototype.numberOfOccurrences = function() {
var valueToFind = arguments[0];
...
}
I would recommend adding the parameter to the function for clarities sake. Seems counter intuitive for a function like numberOfOccurences to not take in a parameter - numberOfOccurences of what?
Fiddle: http://jsfiddle.net/KyleMuir/g82b3f98/
You might try using the locally available variable 'arguments' inside of the function. So for example, your code might look like thsi:
Array.prototype.numberOfOccurrences = function() {
var args = arguments || {};
var testArray, testCheck;
if (args[0] && Array.isArray(args[0]) {
// do something with the array that was the first argument, like:
testArray = args[0];
testCheck = testArray.indexOf(args[1]);
return testCheck;
} else {
// do what you want to do if the function doesn't receive any arguments or the first argument
// received isn't an array.
}
}
'arguments' is always available to you inside a declared function.
I need to change array to a new array created inside a function.
function changeArr(a)
{
a=["hello"]; // don't work
//a.push("hello"); //works, but the real array pretty big (dont want copy)
}
var arr=[];
changeArr(arr);
console.log(arr); // should echo ["hello"]
It seems like all you really want to do is clear the array that is passed into the function, before appending to it:
function changeArr(a)
{
a.length = 0; // clear the array here if you don't care about the prev. contents
a.push("hello"); // this adds to the array that was passed in
}
Inside the function changeArr(), a is only a local variable referencing the array you passed as an argument when calling this function. a=["hello"] makes this local variable reference a newly created and different array. This changes does not affect the original array passed in. What you want to do is likely what Miky Dinescu suggested: use the local variable to modify the original array but don't assign/attach anything new to it.
If you are trying to completely replace the array, you can use a return value.
function changeArr()
{
return ["hello"];
}
arr = changeArr();
If there is a reason you aren't doing this, explain and I'll adjust my answer.
You can use the splice method as such:
a.splice(0,a.length,"hello")