i'm trying to add together the contents of an array (integers).
for example:
var myArray;
var answer;
myArray[0]=2;
myArray[1]=5;
answer=myArray[0]+myArray[1];
answer should equal 7.Could you help me, please? Thank you so much.
You need to initialize your array
var myArray = [];
As you get more values into your array you might consider a loop, example:
var myArray = [];
var answer = 0;
myArray[0]=2;
myArray[1]=5;
for (var i=0;i<myArray.length;i++)
{
answer += myArray[i];
}
console.log(answer);
Take a look at this: http://www.w3schools.com/js/js_loop_for.asp
When I run your code, I get an error.
you need to intialize your variable myArray to be an array.
var myArray = [];
After I do that, answer has the expected value.
You need to declare myArray as an array, otherwise myArray[0] means a property named 0 on undefined (which will probably blow up) rather than an index access.
var myArray = [];
...
Related
I am trying to push items from one Array to another depending on the order that is supplied. Essentially i have a 2d array with a name and a price :
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
Another array with the order it should be in :
var myOrder = [0,2,1];
My resulting array would look like this :
var finalArray = [['Apples',22],['Berry',23],['Orange',55]]
My initial thought process was to loop through myArray and loop through myOrder , store the object temporary at a specified index in myOrder then push to final array. I think i am over thinking it a bit, i made several attempts but with no luck whatsoever. Any help would be greatly appreciated!
This is a simple map() that doesn't require anything else
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
let final = myOrder.map(i => myArray[i])
console.log(final)
The optimal way appears to me to be:
Initialize empty finalArray
Loop over your myOrder array
2.1. Push myArray[index] to finalArray
Like so:
let finalArray = [];
for(let index of myOrder) {
finalArray.push(myArray[index]);
}
Review the for...of syntax if you're not familiar with it.
You can use splice to insert so long as the same number of elements are present in both the arrays.
You iterate over the myOrder array and then use splice, to which the index of the new array is the current value of the iteration and then use array present in the index position of myArray
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
var finalArray = [];
myOrder.forEach(function(val, index) {
finalArray.splice(val, 0, myArray[index]);
});
console.log(finalArray);
Easy enough using .reduce:
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
function reorder(array, order) {
return order.reduce((newArray, orderIndex) => {
newArray.push(array[orderIndex]);
return newArray;
}, []);
}
console.log(reorder(myArray, myOrder))
function reorder(arr, order) {
return order.map(function(i) {
return arr[i];
});
}
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
reorder(myArray, myOrder); // => [["Apples",22],["Berry",23],["Orange",55]]
One of way solving this will be
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
var finalArray;
for (x in myOrder) {
finalArray[x] = myArray[myOrder[x]];
}
This is a beginning level solution. Also you use libraries available for java script such as underscore.js(http://underscorejs.org/) for such operations on Array and Object.
Also you can use ECMA 6, for doing this which will reduce your line of coding.
Example-
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
let finalArray = myOrder.map(i => myArray[i])
This is the new way of coding in javascript.
In my point of view, it will be easy if you learn latest version of Java script(ECMAscript 6)
i have array like this
[["apple","banana"],["monkey"]];
how can i associate key to them like,
[{"fruit":["apple","banana"],"wild":["monkey"]}]
is this possible?
i'm trying something like this
var arr = [["apple","banana"],["monkey"]];
var newArray = [];
for(var i=0;i<arr.length;i++){
newArray["fruit"] = arr[i] //further code i don't know
}
help me th
While you can do that, like this:
var array = [["apple","banana"],["monkey"]];
var update = [
{fruit: array[0], wild: array[1]}
];
console.log(update);
...frankly it seems unlikely that's really want you want.
Very simply you can assign a new name simply
var array = [["apple","banana"],["monkey"]];
var names = ["fruits", "wild"]
var modified = [{names[0]: array[0], names[1]: array[1]}];
If you have a lot of values just use a for loop to iterate and assign value to it.
I have 3 arrays like:
var arr1 = [];
var arr2 = [];
var arr3 = [];
//When I want to add something into array then I use
arr1.push("text");
arr2.push("text");
but is it possible to make something like the following example?
//example:
var arr = [];
arr['group1'].push("text1");
arr['group2'].push("text2");
arr['group2'].push("textn");
//and then iterate like:
for(item in arr['group1'])
console.log(item);
is it even possible to do something like that? I have tried but does not work.
There's a fundamental misunderstanding though, arr is an array but you're using it as an associative array, which in JavaScript is better represented with an object {}. for...in is for objects, NOT arrays, the MDN has a warning note about it:
for..in should not be used to iterate over an Array where index order
is important...
I would advice even if index is trivial to use a regular for loop or a forEach.
Consider using the following, more appropiate approach.
var obj = {
group1: ['text1'],
group2: ['text2'],
group3: ['text3']
};
// pushing more strings
obj.group1.push('foo');
obj['group2'].push('baz');
You're treating arr['group1'] as an array (by using .push()), but you haven't declared it as an array.
var arr = [];
arr['group1'] = [];
arr['group2'] = [];
arr['group3'] = [];
arr['group1'].push("text1");
arr['group2'].push("text2");
arr['group2'].push("textn");
It seems you're actually looking for Javascript Objects instead of arrays.
Also, you need to create these objects first.
var obj = {group1:[],group2:[],group3:[]};
/* or
var obj = {};
obj.group1 = [];
*/
obj['group1'].push("text1");
// or obj.group1.push("text1");
The for...in structure sets your for variable to the key, not the value. Assuming arr['group1'] is an array, this will work fine:
//example:
var arr = [];
arr['group1'].push("text1");
arr['group2'].push("text2");
arr['group2'].push("textn");
//and then iterate like:
for(item in arr['group1'])
console.log(arr['group1'][item]);
I have a global array in javascript say
jsonArr = ["location","department","grade"];
now inside my method i am doing this
var newArr = [];
newArr = jsonArr;
var sorted_arr = newArr.sort();
my newArr is getting sorted but problem is along with jsonArr also got sorted i dont want to sort jsonArr
what is the problem can anyone plz help me ?
newArr and jsonArr are referencing the same array in your code (that's what happens when you simply assign one array to another, like you're doing with this statement: newArr = jsonArr;). You need to copy the array first; you can use the slice method for that:
var newArr = jsonArr.slice(0);
var sorted_arr = newArr.sort();
In line newArr = jsonArr; you assing reference of jsonArr to the newArr, which means this two variables will point to the same place in memory (one array). You must copy array explicit before sorting.
newArr = [].concat(jsonArr);
var newArr = $.extend(true, [], jsonArr);
var sorted_arr = newArr.sort();
You need to make a deep copy. Alternatively you can use the Array.slice() method (http://www.w3schools.com/jsref/jsref_slice_array.asp) which actually gives you a better handle.
Hope that helps!!
In the following code sample i get a strange behavior
var data = ['xxx', 'yyy'];
for (var i in data)
{
var a = i;
var b = data[i];
}
The two first iterations works just fine. I get index "0" and "1" in i, but then it loops one extra time and now the i is "sum". Is this by design or what is this extra iteration used for? The result in my case is always empty and it messes up my code. Is there a way to not do his extra loop?
BR
Andreas
It looks like you (or some other code you've included) have added extra properties onto the Array prototype. What you should be doing is checking to see whether the object you're iterating over actually has that property on itself, not on its prototype:
for (i in data) {
if (data.hasOwnProperty(i)) {
a = i;
b = data[i];
}
}
That said, you should never use for .. in on arrays. Use a regular for loop.
See here for more information: http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
You are looping through an Array, not through an Object. For arrays it's better to use:
for (var i=0; i<data.length; i=i+1){
/* ... */
}
In your loop every property of the Array object is taken into account. That makes the for ... in loop for array less predictable. In your case it looks like sum is a property (method) that's added to Array.prototype elsewhere in your code.
There are more ways to loop through arrays. See for example this SO-question, or this one
Just for fun, a more esoteric way to loop an array:
Array.prototype.loop = function(fn){
var t = this;
return (function loop(fn,i){
return i ? loop(fn,i-1).concat(fn(t[i-1])) : [];
}(fn,t.length));
}
//e.g.
//add 1 to every value
var a = [1,2,3,4,5].loop(function(val){return val+1;});
alert(a); //=> [2,3,4,5,6]
//show every value in console
var b = [1,2,3,4,5].loop(function(val){return console.log(val), val;});
Here's a way to safely iterate.
var data = ['xxx', 'yyy'];
for (var i = 0; i < data.length; i++)
{
var a = i;
var b = data[i];
}
What you are getting is an method coming from extending the Array object, I guess you are using some library where is something like
Array.prototype.sum = function () {...};
Perhaps setting data like this would work better: var data = {0:'xxx', 1:'yyy'};
First of all data is an object. Try to add console.log(a); and console.log(b); inside your loop and you'll see.