How do you push a specified number of objects to an array? - javascript

I'm pretty new to javascript but I'm trying to push a specified number of objects to an array using the following code. When I check the console I see only one object is pushed to the array. What should I be doing differently? Thanks!
var albums = {};
function collection(numberOfAlbums) {
array = [];
array.push(albums);
return array;
};
console.log(collection(12));

From your code:
array.push(albums);
would add the same object each time (assuming you had added a loop) which isn't what you want.
This will add a new empty object for each iteration of numberOfAlbums:
function collection(numberOfAlbums) {
for (var array = [], i = 0; i < numberOfAlbums; i++) {
array.push({});
}
return array;
};
Here's another way using map. Array.apply trick from here.
function collection(numberOfAlbums) {
var arr = Array.apply(null, Array(numberOfAlbums));
return arr.map(function (el) { return {}; });
};

I could give you the code but that is not learning. So here are the steps:
use numberOfAlbums as an argument in a function.
create an empty array.
use numberOfAlbums in for-loops in that for-loops push albums. ==array.push(albums)== do not use {}curly brackets around albums.
return the array.

Related

Object Keys to Array

The challenge asks us to create an array from a given object's keys (without using Objects.keys).
Here is my code:
function getAllKeys(object){
var array = [];
for(var key in object){
array.push(key);
return array;
}
}
var myObj={
name:"bellamy",
age:25 };
getAllKeys(myObj);
For some reason it's only returning the first key
[ 'name' ]
Any help would be much appreciated! I'm sure it's a simple fix, just one I'm not aware of as an extreme novice.
You need to move your return outside of your loop:
function getAllKeys(object){
var array = [];
for(var key in object){
array.push(key);
}
return array;
}
var myObj = {
name:"bellamy",
age:25
};
getAllKeys(myObj);
This is because your function will immediately return when it first encounters return, which in your example is in the first iteration of the loop.

Typescript foreach variable not available

I have a foreach loop where I create a new temp array, then run a nested foreach loop. I'm then trying to access the temp array inside the nested foreach loop, but it's coming back with a "variable not available" error.
let final = {
array: []
};
myArray.forEach(item =>
{
let newObject = { items: [] };
item.subArray.forEach(subItem =>
{
var subObject = { prop: subItem.prop };
// Error here: "newObject is not available"
newObject.items.push(subObject);
});
// Error here: "final is not available"
final.array.push(newObject);
});
I know I can provide this to the array by providing it as an argument (eg: item.subArray.forEach(subItem => {},this);)
but this doesn't help me because tempArray doesn't exist at the class level.
I have the same problem when I try to assign my temp array to the "final" array declared outside the foreach.
Is there a way I can access the parent scope from within the foreach?
I should point out this code exists within a function defined on a class. I'm basically trying to aggregate properties with a certain value from within the subarray
Screenshot showing the issue: http://i.imgur.com/HWCz0Ed.png
(The code visible in the image is within the first forEach loop)
Update: I figured this out, it was an issue between using let and var. See my answer below for details.
The code you pasted into the question must not be your real code. if it was you would have had no problem accessing finalArray.
The results of both your snippets are very different.
the first will give you an array of all the properties of the sub item of the last item.
the seconds will give you an array of arrays where each array contains the properties of the sub item
If I understand correctly what you want is to get a single array containing all the properties of all the sub items. so you want to map each item to an array of sub-item properties and then flatten the result into a single array.
How about this?
var items = [
{subitems:[
{prop:1},
{prop:2},
]},
{subitems:[
{prop:3},
{prop:4},
]},
]
var result = items.map(function(item){
return item.subitems.map(function(subitem){
return subitem.prop;
})
}).reduce(function(prev,curr){
return prev.concat(curr);
},[]);
console.log(result);
Update: I finally figured this out. In my actual code I was creating newObject using TypeScript's let keyword. I changed it to var instead and it started working.
Chalk that up to me not understanding the difference between let (block scope) and var (global scope) - d'oh!
The solution listed below also worked for me, but simply changing let to var has meant that my original code works perfectly.
I solved this by using map() instead of forEach():
var final = {
array: []
};
var finalArray = myArray.map(function (item)
{
let newObject = { items: [] };
var tempArray = item.subArray.map(function (subItem)
{
var subObject = { prop: subItem.prop };
return subObject;
});
newObject.items = tempArray;
return newObject;
});
final.array = finalArray;

Creating a function, iterating through arrays, and pushing names

I am new to javascript and still trying to figure things out. I know little about basics and I ran into this problem and I'm not sure which line of code is wrong. Also, I'm trying to figure out how to console.log lines of code. Any help would be appreciated. Thank you!
Create a function named functions.imHere that creates and returns a new array. Within the function, iterate through the students array and use the .push() method to add each student to the new array.
here is my code:
functions.imHere = function() {
for(var i = 0; i < students.length; i++) {
newArray.push(students[i]);
return newArray;
}
};
Is this what you are looking for? Instantiate array before loop, insert elements inside the loop and return after the loop. Assuming that students is accessible within your function, otherwise you have pass students as an argument to your function.
functions.imHere = function() {
var newArray = [];
for(var i = 0; i < students.length; i++) {
newArray.push(students[i]);
}
return newArray;
};

Javascript map method on array of string elements

I am trying to understand how to implement the map method (rather than using a for loop) to check a string for palindromes and return boolean values for whether the mapped array elements reversed are the same as the original array elements. I cannot seem to understand the syntax of the map method. How do I get the map to function on each element in the original array? What is the value? Here is my working code, which is only logging a value of undefined:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.map(function (item) {
item.split("").reverse().join("");
return newArray === myArray;
});
}
console.log(palindromeChecker("What pop did dad Drink today"));
Here is a link to the fiddle:
https://jsfiddle.net/minditorrey/3s6uqxrh/1/
There is one related question here:
Javascript array map method callback parameters
but it doesn't answer my confusion about the syntax of the map method when using it to perform a function on an array of strings.
The map method will literally 'map' a function call onto each element in the array, take this as a simple example of increasing the value of each integer in an array by 1:
var items = [1,2,3];
items.map(function(item) {
return item + 1;
});
// returns [2,3,4]
In your case, you are trying to use map to accept or reject a string if it's a palindrome, so a simple implementation might be:
var items = ['mum', 'dad', 'brother'];
items.map(function(item) {
return item.split('').reverse().join('') === item;
});
// returns [true, true, false]
I'm not 100% sure of your reasons for using map, because if you were trying to just filter the array and remove the strings that aren't palindromes, you should probably use the filter method instead, which works in the same way, but would remove any that return false:
var items = ['mum', 'dad', 'brother'];
items.filter(function(item) {
return item.split('').reverse().join('') === item;
});
// returns ['mum', dad']
In your case you are splitting a string first to get your array of characters; you may also want to make that string lower case and remove punctuation, so an implementation might be:
var string = 'I live at home with my Mum, my Dad and my Brother!';
var items = string.toLowerCase().replace(/[^a-z0-9-\s]+/, '').split(' ');
items.filter(function(item) {
return item.split('').reverse().join('') === item;
});
// returns ['i', 'mum', dad']
As mentioned in one of the comments on your question, you need to ensure you return a value from your function if you are using a separate function to perform the check, so this is how your function should look:
function checkPalindromes(string) {
var items = string.toLowerCase().replace(/[^a-z0-9-\s]+/, '').split(' ');
items.filter(function(item) {
return item.split('').reverse().join('') === item;
});
return items;
}
And you would call it using:
checkPalindromes('I live at home with my Mum, my Dad and my Brother!'); // ['i', 'mum', 'dad']
try something like this:
let str = 'hello';
let tab = [...str];
tab.map((x)=> {
console.log("|"+x+"|");
return x;
})
newArray should include reversed version of theall items in myArray. After that, newArray should be reversed and joined with space in order to get the reversed version of the input string.
Here is the code:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.map(function (item) {
return item.split("").reverse().join("");
});
console.log(newArray);
return newArray.reverse().join(" ") === string;
}
console.log(palindromeChecker("dad did what"));
Javascript map method on array of string elements by using split() function.
let str = 'hello';
str.split('').map((x)=> {
console.log("|"+x+"|");
return x;
})
Map is a higher-order function available in ES5. I think your newArraywill contain an array of boolean values.
In essence, map will iterate over every value in your array and apply the function. The return value will be the new value in the array. You can also use map and save the information you need somewhere else, and ignore the result of course.
var arr = [1,2,3,4];
var newArray = arr.map(function(i) {
return i * 2;
});
//newArray = [2,4,6,8]
The map function in javascript (and pretty much in any language) is a great little function that allows you to call a function on each of the items on a list, and thus changing the list itself.
The (anonymous) function you're passing as an argument accepts an argument itself, which is filled by an item of the list it is working on, each time it is called.
So for a list [1,2,3,4], the function
function(item) { return item + 1 }, would give you a list of [2,3,4,5] for a result. The function you passed to $.map() is run over each element of the list, and thus changing the list.
So for your code: in the function you're passing as an argument to $.map(), you're returning whether the old and new array are equal (which is false btw). So since you're returning a boolean value, the list you'll end up with is a list of bools.
What I think you want to do, is extract the newArray == myArray from the function you're passing to $.map(), and putting it after your $.map() call.
Then inside the function you're passing to $.map(), return the item you're splitting and whatnot, so your newArray will be an array of strings like myArray.
Apart from a few minor mistakes in your code, such as scope issues (you're referencing the "newArray" and "myArray" outside of the function in which they where defined, and therefore, getting "undefined")..
The main issue you had is that you addressed the ENTIRE array inside the map function, while the whole concept is breaking things down to single elements (and then the function collects everything back to an array for you).
I've used the "filter" function in my example, because it works in a similar manner and I felt that it does what you wanted, but you can change the "filter" to a "map" and see what happends.
Cheers :)
HTML:
<body>
<p id="bla">
BLA
</p>
<p id="bla2">
BLA2
</p>
</body>
Javascript:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.filter(function (item) {
var reversedItem = item.split('').reverse().join('');
return item == reversedItem;
});
document.getElementById("bla").innerHTML = myArray;
document.getElementById("bla2").innerHTML = newArray;
}
palindromeChecker("What pop did dad Drink today");
Thanks for your input, all. This is the code I ended up with. I fixed the scope issues in the original post. My main problem was understanding the syntax of the map method. In particular, I could not understand from other online resources how to determine the value in the callback function. So, with much help from above I have placed the map method inside the palindromeChecker, and done all of the work on the array inside the map function.
var palindromeChecker = function(string) {
var newString = string.toLowerCase().split(' ');
newString.map(function(item) {
console.log(item.split('').reverse().join('') === item);
});
};
palindromeChecker("What pop did dad drink today");
//Returns false, true, true, true, false, false

How do you search object for a property within property?

I have this object:
key = {
spawn:{type:1,img:app.assets.get('assets/spawn.svg')},
wall:{type:2,img:app.assets.get('assets/wall.svg')},
grass:{type:3,img:app.assets.get('assets/grass.svg')},
spike:{type:4,img:app.assets.get('assets/spike.svg')},
ground:{type:5,img:app.assets.get('assets/ground.svg')}
};
And I have an array with only types and I need to add the given image to it, the array looks something like this:
[{type:1,image:null},{type:3,image:null},{type:2,image:null},{type:2,image:null},{type:5,image:null}]
Basically I want to loop the array, find the type in the key object and get the given image and save it into the array.
Is there any simple way to do this?
One thing that stands out here for me is the line
...get the given image and save it into the array
I'm assuming this means the original array. I think a better approach would be to map the appropriate keys and values to a new array but I've assumed, for this example, that it's a requirement.
In an attempt to keep the solution as terse as possible and the request for a lodash solution:
_.each(key, function(prop){
_.each(_.filter(types, { type: prop.type }), function(type) { type.image = prop.img });
});
Given the object of keys and an array of objects like so:
var key = {
spawn:{type:1,img:app.assets.get('assets/spawn.svg')},
wall:{type:2,img:app.assets.get('assets/wall.svg')},
grass:{type:3,img:app.assets.get('assets/grass.svg')},
spike:{type:4,img:app.assets.get('assets/spike.svg')},
ground:{type:5,img:app.assets.get('assets/ground.svg')}
};
var arr = [{type:1,image:null},{type:3,image:null},{type:2,image:null},{type:2,image:null},{type:5,image:null}];
We can first create an array of the properties in the object key to make iterating it simpler.
Then loop over the array arr, and upon each member, check with a some loop which image belongs to the member by its type (some returning on the first true and ending the loop).
You can change the forEach to a map (and assign the returned new array to arr or a new variable) if you want the loop to be without side-effects, and not to mutate the original array.
var keyTypes = Object.keys(key);
arr.forEach(function (item) {
keyTypes.some(function (keyType) {
if (key[keyType].type === item.type) {
item.image = key[keyType].img;
return true;
}
return false;
});
});
The smarter thing would be to change the object of the imagetypes so that you could use the type as the accessing property, or create another object for that (as pointed out in another answer).
I'm not sure if this solution is modern, but it does not use any loops or recursion.
object = {
spawn: {type:1, img:app.assets.get('assets/spawn.svg')},
wall: {type:2, img:app.assets.get('assets/wall.svg')},
grass: {type:3, img:app.assets.get('assets/grass.svg')},
spike: {type:4, img:app.assets.get('assets/spike.svg')},
ground: {type:5, img:app.assets.get('assets/ground.svg')}
};
arr = [
{type:1, image:null},
{type:3, image:null},
{type:2, image:null},
{type:2, image:null},
{type:5, image:null}
];
var typeImages = {};
Object.getOwnPropertyNames(object).forEach(function(value){
typeImages[object[value].type] = object[value].img;
});
arr = arr.map(function(value){
return {
type: value.type,
image: typeImages[value.type]
};
});
var key = {
spawn:{type:1,img:app.assets.get('assets/spawn.svg')},
wall:{type:2,img:app.assets.get('assets/wall.svg')},
grass:{type:3,img:app.assets.get('assets/grass.svg')},
spike:{type:4,img:app.assets.get('assets/spike.svg')},
ground:{type:5,img:app.assets.get('assets/ground.svg')}
};
var typesArray = [{type:1,image:null},{type:3,image:null},{type:2,image:null},{type:2,image:null},{type:5,image:null}];
for(var i = 0, j = typesArray.length; i < j; i++)
{
typesArray[i].image = getKeyObjectFromType(typesArray[i].type).img;
}
function getKeyObjectFromType(type)
{
for(var k in key)
{
if(key[k].type == type)
{
return key[k];
}
}
return {};
}
for (var i = 0; i < typesArray.length; i++) {
for (prop in key) {
if (key[prop].type === typesArray[i].type) {
typesArray[i].image = key[prop].img;
}
}
}
It loops through the array ("typesArray"), and for each array item, it go through all the objects in key looking for the one with the same "type". When it finds it, it takes that key object's "img" and saves into the array.
Using lodash (https://lodash.com/):
var key = {
spawn:{type:1,img:app.assets.get('assets/spawn.svg')},
wall:{type:2,img:app.assets.get('assets/wall.svg')},
grass:{type:3,img:app.assets.get('assets/grass.svg')},
spike:{type:4,img:app.assets.get('assets/spike.svg')},
ground:{type:5,img:app.assets.get('assets/ground.svg')}
};
var initialList = [{type:1,image:null},{type:3,image:null},{type:2,image:null},{type:2,image:null},{type:5,image:null}];
var updatedList = _.transform(initialList, function(result, item) {
item.image = _.find(key, _.matchesProperty('type', item.type)).img;
result.push(item);
});
This will go over every item in the initialList, find the object that matched their type property in key and put it in the image property.
The end result will be in updatedList

Categories

Resources