JQuery - pushing elements to an array - javascript

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.

Related

json.stringify return null array in javascript [duplicate]

In JavaScript, you can have objects, like this:
var a = { foo: 12, bar: 34 };
Or arrays with key (named) indexes, like this:
var b = [];
b['foo'] = 56;
b['bar'] = 78;
They're somewhat similar, but obviously not the same.
Now the strange thing is, JSON.stringify doesn't seem to take the array. No errors or anything, JSON.stringify(b) just results in [].
See this jsfiddle example. Am I doing something wrong, or do I just misunderstand how arrays work?
Javascript doesn't support Associative arrays (Like PHP).
var b = []; Declaring explicitly an array, when you are trying to create an Object.
Arrays in Javascript can only contain the Index approach of Arrays, while Objects are more of
Associative arrays.
If you change var b = []; to var b = {}; it will solve the problem.
var b = {} Declaring explicitly an Object.
Javascript arrays are objects. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object for details.
Note: if you supply a non-integer value to the array operator in the
code above, a property will be created in the object representing the
array, instead of an array element.
JSON supports only a subset of Javascript. See http://www.json.org/ for details.
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed
list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
A Javascript array that has properties created in the underlying object does not fit into either of these structures because it has both a collection of name/value pairs and an ordered list of values, so there is no simple way to represent such an object directly in JSON.
The JSON.stringify method is defined in the ECMAScript specification. For example, see http://www.ecma-international.org/ecma-262/5.1/#sec-15.12.3.
While there are many details, the bit that is relevant here is how object values are stringified:
If Type(value) is Object, and IsCallable(value) is false
If the [[Class]] internal property of value is "Array" then Return the result of calling the abstract operation JA with argument value.
Else, return the result of calling the abstract operation JO with argument value.
Given your array, despite the addition of parameters to the underlying object, the result is of stringifying the ordered set of array elements, not the underlying object.
There is nothing wrong about adding parameters to an array object, but they are not part of the array and functions or methods that handle arrays might ignore them or deal with them arbitrarily. You have seen that JSON.stringify ignores the additional parameters. Other functions might do otherwise - you will have to find out in each case.
While it is not wrong, it will probably be easier to understand if you do not add properties to array objects. If you want to add properties, start with a non-array object.
Rather than:
var b = [];
b['foo'] = 56;
b['bar'] = 78;
You might use:
var b = {};
b['foo'] = 56;
b['bar'] = 78;
This snap is from IE explorer. See the array is still blank.
Actually the way of inserting the elements to the array is :
1. Use push()
2. insert the elements in the array during declaration
If you want to stringify the array you have to have the data inside the array.
So, now you want to stringify the key value pairs so you have to pass the object as the argument of JSON.stringify() as follows:
var test = {}; // Object
test['a'] = 'test';
test['b'] = []; // Array
test['b'].push('item');
test['b'].push('item2');
test['b'].push('item3');
var json = JSON.stringify(test);
alert(json);
Solution to your problem now:
Note: Console of Google Chrome is giving different result, which is a bug in Google Chrome.

How to retrieve the first item in an array in 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.

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

Saving a function in an array, and retrieving its index

How can I get the index of a function stored in an array? The following code returns -1
var myArray = [ function(){console.log('fct1')} ];
myArray.indexOf( function(){console.log('fct1')} );
jsFiddle
More details:
I'm using jQuery to delegate events. Each event has one or more callback functions to call. It's impossible for me to know what the functions are since they are not pre-coded. Each callback function will be stored in an array. When a new callback function is added, I want to verify that it isn't already in the array, to avoid duplicates which would be both called by the event.
Any object in JavaScript will not be equal to something similar, except itself.
var func = function() {
console.log('fct1')
};
console.log(Object.prototype.toString.call(func));
# [object Function]
Since functions are also objects in JavaScript, you cannot search for a function object with another function object which does the same.
To be able to get a match, you need to use the same function object, like this
var func = function() {
console.log('fct1')
};
var myArray = [func];
console.log(myArray.indexOf(func));
# 0
This happens due to multiple references.
Each function you declared has a different reference and is not equal to the other.
That's why indexOf doesn't identify it.
Try this:
var func = function(){console.log('fct1')};
var myArray = [func];
alert(myArray.indexOf(func)); // will alert 0.
Fiddle

Iterating an associative array with jQuery .each

Probably the most contributing factor for this question is that I am extremely sleepy right now.
I have an array, which I initiate:
var cells = [];
Then i put some values in it (jQuery objects), for example:
$("td").each(function () {
var td = $(this);
cells[td.attr("id")] = td;
});
And now my problem. This code:
$(cells).each(function (i) {
console.log(this) // firebug console
});
logs absolutelly nothing. When i changed the associative array to a normal, number index one by substituting
cells[td.attr("id")] = td;
with
cells.push(td);
It worked correctly.
Also, when I try to iterate with the for..in loop it works as expected.
for (var cell in cells) {
console.log(cells[cell]);
}
Doeas that mean that jQuery's .each method does not accept associative arrays or am I doing something wrong?
JavaScript does not have associative arrays. It has Arrays and it has Objects, and arrays happen to be objects. When you do this:
var a = [];
a['foo'] = 'bar';
..you're actually doing the equivalent of this:
var a = [];
a.foo = 'bar';
// ^--- property of object 'a'
That is to say you're actually adding a property called foo to the object a, not adding an element to the array a.
From the documentation for jQuery.each():
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. Other objects are iterated via their named properties.
Since you created an Array ([]) jQuery looks at its length property, and since you have not added any elements to the array (only properties on the object, remember) its length is still zero and so jQuery (correctly) does nothing.
What you want to do instead, as others have noted, is create an Object using e.g. var cells = {};. Since a non-Array object has no length property (not by default, anyway) jQuery will know that you really want to iterate over its properties instead of numeric indices as in an Array.
You seem to be thinking Javascript's arrays are associative, which is not the case. You're probably looking for objects (or hashes) instead:
var cells = {}; // Not [].
$("td").each(function() {
var td = $(this);
cells[td.attr("id")] = td;
});
$.each(cells, function() {
console.log(this); // This should work as expected.
});
use $.each(cells, function(i) { ... }) instead of $(cells).each(function...)
The $.each() function is different from the $(selector).each function.

Categories

Resources