I have to write a function that will create an array filled with the indicated number of objects that represent three "types" of these objects.
WITHOUT using for or while loop and not doing that manually?
I don't know how can I add these objects into the array.
I'm choosing the type of object by random, but how can I add them to the array?
these are the objects:
var bestaccount=function(){
var amount=0;
this.pay=function(howmuch){amount+=howmuch;};
this.widthdraw=function(howmuch){amount-=howmuch;};
this.saldo=function(){return amount;};
};
var toGive= function(){
var amount=0;
this.pay=function(howmuch){amount+=howmuch;};
this.saldo=function(){return amount;};
};
var toWithdraw=function(){
var amount=0;
this.withdraw=function(howmuch){amount-=howmuch;};
this.saldo=function(){return amount;};
};
For example there are 3 toWithdraw objects, 1 bestAccount and 1 toGive. I want them all in one array.
EDIT:
Sorry, I was using completely wrong functions.
If anyone needs it, I'm doing it with apply().
Here's the code:
function fillArrayWithNumbers(n) {
arr = Array.apply(null, Array(n));
tabl= arr.map(function (x, i) { return new objects[Math.floor(Math.random()*objects.length)](); });
return tabl;
}
Sorry, but no stress guys. Everyone started somehow.
Now that you have answered your own question, I see that I have misinterpreted it. Anyway, here is how to add objects to an array:
You can add new elements to an array with push like this:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
Now, instead of an array with strings, you want an array with objects. So you can first create the object like this:
var myObject = {numberOfGive: 1, numberOfWithdraw: 3, numberOfBestAccount: 1};
And then push it to your array:
var myArray = [];
myArray.push(myObject);
Source
here's my solution:
var objects =[bestaccount,toGive,toWithdraw];
function fillArrayWithNumbers(n) {
arr = Array.apply(null, Array(n));
tabl= arr.map(function (x, i) { return new objects[Math.floor(Math.random()*objects.length)](); });
return tabl;
}
Thanks for response.
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 can't seem to figure out as to why I am unable to append a value to my array below? Is there a special syntax to follow or something when constructing an array like in the method used below?
var arr = {
"fruits": ['apple','banana','orange']
};
arr.push({ "fruits":"testing123"}); // This line fails
alert(arr["fruits"]);
Try: arr.fruits.push("mango");
You can't push() to an object. You should either use the key-value notation:
arr.anotherFruits = "testing123"; // another key
arr.fruits = "testing123"; //to overwrite
Or make arr actually array:
var arr = [
{"fruits": ['apple','banana','orange']}
]
arr.push({ "fruits":"testing123"})
alert(arr["fruits"])
In this case you'd get
var arr = [
{"fruits": ['apple','banana','orange']},
{"fruits":"testing123"}
]
Or in case you did want to get an object like this
var arr = {
"fruits": ['apple','banana','orange','testing123']
}
you should've used arr.fruits.push('testing123');
Your array defintion is all wrong. Assuming you want arr to be an object that has an array under fruits and then push another value inside fruits, use the following:
var arr = {
fruits: ['apple', 'banana', 'orange']
};
arr.fruits.push("testing123");
console.log(arr["fruits"]);
Change your initial arr declaration to this...
var arr = [{
"fruits": ['apple','banana','orange']
}];
Then you can push more objects onto it. E.g.
arr.push({"fruits": ['mango', 'pear', 'tomato']});
Or, if you wish to push fruits to the existing array INSIDE your object, then simply use your existing arr declaration and use it like this...
arr.fruits.push('tomato');
arr.fruits.push('pear');
arr.fruits.push('tomato');
I'd argue that you don't really require this to be an object at all here.
All you need is this...
var fruits = [];
fruits.push('banana');
fruits.push('apple');
It's simply an array of fruits. If you need more complex structure, then use an array of objects, instead of strings.
Array has push() method, but Object does not. Here you create an Object, but not an Array. So it failed.
I have an Object array that looks like the following:
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
And I want to convert it to look like this:
var newArray = [
1, 2, 3
]
So it's basically taking the object array, extracting the id's out of the objects, and creating a new array that contains the id's that were extracted. Is there a way to do this in one line? Even better if a new array doesn't have to get created and array is just updated.
var test ="sai";
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
console.log(array.map(function(obj){return obj.id}))
iterate the array using foreach and populate newArray
var newArray = [];
array.forEach(funtion(element){
newArray.push(element.id);
});
console.log( newArray );
array.map(function (item) {
return item["id"];
}
If you'd like to have anew instance of the mapped array:
var newarray = [];
array.forEach(function (item) {
newarray.push(item["id"]);
}
array.map(function(element) {return element.id})
OP Requirement: better if array is just updated
array = array.map(function(element) {return element.id})
This question already has answers here:
Copy array by value
(39 answers)
Closed 8 years ago.
I have an array example fruit . I'd like to copy it as array fruits2, without keeping reference.
As in the following example reference is kept so fruits is modified.
var fruit = function (name){
this.name = name;
}
var fruits = [];
fruits.push(new fruit('apple'));
fruits.push(new fruit('banana'));
fruits.push(new fruit('orange'));
var fruits2 = fruits;
fruits2.length = 0;
console.log(fruits);
http://jsfiddle.net/vkdqur82/
Using JSON.stringify and JSON.parse does the trick but the objects in fruits2 are not any longer of type fruit but are of general type object
var temp = JSON.stringify(fruits);
var fruits2 = JSON.parse(temp);
I would like to know an alternative approach which would keep inner object of fruit.
Use slice: var fruits2 = fruits.slice(); should do it.
Your jsFiddle, modified
See also: MDN
**Edit. I was a bit lazy, let's correct my answer to make up for that.
For an Array of just values slice is perfect. For an Array of objects or arrays or a mix of values/objects/arrays, the Array and Object elements of the Array to clone need cloning too. Otherwise they will be references to the original arrays or objects (so: not copies) and a change of one [of these references of arrays or objects] will be reflected in all 'clones' containing a reference to it.
To clone an Array of Arrays/Objects/mixed values Array.map is your friend. There are several methods to think of:
creating a new instance with old data
var fruits1 = fruits.map(function(v) {return new Fruit(v.name);});
using JSON
var fruits2 = fruits.map(function(v) {return JSON.parse(JSON.stringify(v));});
create and use some cloning method
var fruits3 = fruits.map(function(v) {return cloneObj(v);});
In case 3, a method for cloning could look like:
function cloneObj(obj) {
function clone(o, curr) {
for (var l in o){
if (o[l] instanceof Object) {
curr[l] = cloneObj(o[l]);
} else {
curr[l] = o[l];
}
}
return curr;
}
return obj instanceof Array
? obj.slice().map( function (v) { return cloneObj(v); } )
: obj instanceof Object
? clone(obj, {})
: obj;
}
Using this cloneObj method, Array.map is obsolete.
You can also use var fruitsx = cloneObj(fruits);
The jsFiddle from the link above is modified to demonstrate these methods.
For Array.map, see again MDN
slice can do the trick.
You can also use .map but .slice is normally faster.
var copy = fruits.map(function(item) {return item});
Hope it helps
You can declare a new array and use concat method, so that you concat all values from your array to the new array. Something like this:
var x = ["a","b"];
var a = [];
a = a.concat(x);
console.log(a);
I edited my poor answer.
Best regards.
I'm hoping my question is using the correct terminology...
Can someone explain to me how I can perform the following:
If I have an array consisting of:
Object { id=1498, brandName="Booths", quality="Standard"}
Object { id=1499, brandName="Booths", quality="Standard"}
How can I iterate throughout that array and return another array of distinct 'keys'?
Ultimately I want an array which would return something like:
[id,brandName,quality] (but the original array is going to return different keys at different times.
Have I made sense?
You can use Object.keys:
var a1 = [{ id:1498, brandName:"Booths", quality:"Standard"},
{ id:1499, brandName:"Booths", quality:"Standard"}],
a1Keys = a1.map(function(a){return Object.keys(a);});
//a1Keys now:
[['id','brandName','quality'],['id','brandName','quality']]
The keys method is described #MDN, including a shim for older browsers
var a = {"a": 1, "b": "t" };
var keys = new Array();
for(var o in a){
keys.push(o);
}
console.log(keys)