How to fill an array with a for loop? - javascript

I’m having a lot of trouble learning how to use for loops to fill a new variable. As an example say if I have var year = [2010, 2000, 1992]; and var age = [];.
How would I use a for loop to fill in the age variable?
If this is a bad example, don’t use this. I just would like some help with understanding how to fill in empty arrays.
var names = ["Ace", "yoshi", "Lassie"];
var age = [25, 23, 5];
var u24 = [];
for (var i = 0; i < names.length; i++) {
if ([age] < 24) {
u24 += age[i]
console.log("hello " + names + " " + "you are" + age);
}
}

It is better to create objects that contain relevant data. Combining the name and age into a person object would help.
var persons = [
{
name: "Ace",
age: 25
},
{
name: "yoshi",
age: 23
},
{
name: "Lassie",
age: 5
}
];
var u24=[];
for (var i =0; i < persons.length; i++) {
var person = persons[i];
if(person.age < 24){
u24.push(person.age);
console.log("hello " + person.name + " " + "you are " + person.age);
}
}
console.log(u24);
But you can also use forEach like this:
var persons = [
{
name: "Ace",
age: 25
},
{
name: "yoshi",
age: 23
},
{
name: "Lassie",
age: 5
}
];
var u24=[];
persons.forEach(
function(person) {
if(person.age < 24){
u24.push(person.age);
console.log("hello " + person.name + " " + "you are " + person.age);
}
}
);
console.log(u24);
By making objects that include all relevant data your loops will never get out of sync. If you remove a person from the persons array then their name and age will go together.
UPDATE: Using a filter
var persons = [
{
name: "Ace",
age: 25
},
{
name: "yoshi",
age: 23
},
{
name: "Lassie",
age: 5
}
];
var youngPersons = persons.filter(
function(person) {
return (person.age < 24);
}
);
console.log(youngPersons);
Or using an ES6 Arrow Function
var persons = [
{ name: "Ace", age: 25 },
{ name: "yoshi", age: 23 },
{ name: "Lassie", age: 5 }
];
var youngPersons = persons.filter((person) => person.age < 24);
console.log(youngPersons);
This provides back an array of the persons that match your Age under 24 criteria.

If all you want to do is fill in the age array with a loop, you can try this:
let years = [2010, 2000, 1992],
age = [],
d = new Date().getFullYear();
years.forEach(year => age.push(d - year));
console.log(age);
As regards the relationship between age and names, I think Intervalia has explained that.

A working version.
Please compare it with your code to see the differences. Arrays always got me when I was starting out, and the syntax with different across languages, despite the reuse of bracket symbols.. AutoIt language still trips me up :P
var names = ["Ace", "yoshi", "Lassie"];
var age = [25, 23, 5];
//Use array.push() to append values
var u24 = [];
//variable i counts up to names.length
//because i++ means 'add one' to i
for (var i = 0; i < names.length; i++) {
//if ([age] < 24) {u24 += age[i];
//age at the count 'i' (which is
//counting)
//is achieved by array[at_index]
if (age[i] < 24) {
u24.push(age[i]); //add it to the end
console.log("Hello " + names[i] +
", you are " + age[i]);
}
}

Related

Need help correcting & combining two functions into one

The Question is
Create a function called divisibles() that will take each object in upper and find all
objects in lower that evenly divide into it, ignoring zero. The function should return an
object that is upper but each object has an additional key called found and the value
for that key is an array containing each item from lower that was evenly divided into it.
Output the result of the function to the console.
Here's my code so far, I know I'm doing something very wrong and can't figure it out. I have it in two functions, can't figure out how to make it one, and my output doesn't look correct either.
function divisibles(number, myArrayLower) {
let divisibleArray = [];
let count = 0;
for (let i = 0; i < myArrayLower.length; i++) {
if (number % myArrayLower[i].value === 0) {
divisibleArray[count++] = {name: myArrayLower[i].name, value: myArrayLower[i].value};
}
}
return divisibleArray;
}
function findDivisibles(myArrayUpper, myArrayLower) {
let divisiblesArray = [];
for (let i = 0; i < myArrayUpper.length; i++) {
let divisibleArray = divisibles(myArrayUpper[i].value, myArrayLower);
divisiblesArray[i] = {
name: myArrayUpper[i].name, value: myArrayUpper[i].value,
found: divisibleArray
};
}
return divisiblesArray;
}
Here's the call function
let resultArray = findDivisibles(myArrayUpper, myArrayLower);
Here is my console.log
let resultArray = findDivisibles(myArrayUpper, myArrayLower);
for (let i = 0; i < resultArray.length; i++) {
console.log("Name: " + resultArray[i].name + " Value: " + resultArray[i].value + " Found: ");
let tmpArray = resultArray[i].found;
for (let k = 0; k < tmpArray.length; k++) {
console.log(" Name: " + tmpArray[k].name + " Value: " + tmpArray[k].value);
}
}
The desired output will look something like this
{
name: ”Nathan15”,
value: 15,
found:[
{ name: “nathan3”, value: 3},
{ name: “nathan15”, value: 15} ]
}
This is my output
My output looks like this
Name: Nathan586 Value: 2930 Found:
Name: Nathan587 Value: 2935 Found:
Name: Nathan588 Value: 2940 Found:
Name: nathan1 Value: 3
Name: nathan2 Value: 6
Name: nathan4 Value: 12
I can add the rest of the question, code I wrote for previous parts of this question if it helps

Sort two inter-related arrays (players and scores) and print results?

I would like to enter 3 players with 3 scores in using 2 arrays.
For now I stuck, concerning the ranking; how to do ???
Small example:
Player 1 : Jeremy
Score Jeremy : 12
Player 2 : Julien
Score Julien : 18
Player 3 : Olivia
Score Olivia : 22
For the ranking we should have
The first => Olivia with 22 scores
The second => Julien with 18 scores
The third => Jeremy with 12 scores
Here is my code.
function main() {
var players = new Array();
var scores = new Array();
for(i = 0; i<3; i++) {
players[i] = prompt("Player " + (i+1) + " : ");
scores[i] = prompt("Score " + (players[i]) + " : ");
}
}
Thank you advance.
Splitting data into two arrays is probably not the easiest way to go, but assuming you have no choice, I would use a custom sorting function and an additional array containing indices related to the other arrays :
main();
function main() {
var players = new Array();
var scores = new Array();
var ranking = new Array();
for (var i = 0; i < 3; i++) {
ranking[i] = i;
players[i] = prompt("Player " + (i + 1) + " : ");
scores[i] = prompt("Score " + (players[i]) + " : ");
}
indirectSort(3, ranking, scores);
for (var i = 0; i < 3; i++) {
var ithPlayer = players[ranking[i]];
var ithScore = scores[ranking[i]];
console.log(ithPlayer, ithScore);
}
}
function indirectSort (n, toBeSorted, toBeCompared) {
for (var i = 0; i < n - 1; i++) {
for (var j = i + 1; j < n; j++) {
var a = toBeCompared[toBeSorted[j]];
var b = toBeCompared[toBeSorted[i]];
if (a < b) {
var min = toBeSorted[j];
toBeSorted[j] = toBeSorted[i];
toBeSorted[i] = min;
}
}
}
}
Here is how the above code works :
players = ["John", "Jack", "Bob"];
scores = [2, 1, 3];
ranking = [0, 1, 2];
indirectSort(3, ranking, scores);
console.log(ranking);
// [1, 0, 2]
console.log(players[ranking[0]]);
// "Jack"
console.log(scores[ranking[0]]);
// 1
This will give you a sorted Players array, where each player has a name and a score
function main()
{
var players = new Array();
for(i = 0; i<3; i++){
let player = {};
player.name = prompt("Player " + (i+1) + " : ");
player.score = prompt("Score " + (players[i]) + " : ");
players[i] = player;
}
players.sort(function(a,b){
if (a.score < b.score)
return -1;
if (a.score> b.score)
return 1;
return 0;
})
console.log(players);
}
You could and should be storing each user as an object in an array like this:
function main(){
var players = [];
for(var i = 0;i<3;i++){
var player = {};
player.name = prompt("Enter user name");
var ranking = prompt("Enter user ranking");
player.ranking = parseInt(ranking);
players.push(player)
}
console.log("Players");
players.forEach(function(player){
console.log(player.name,player.ranking);
});
//Now sort based on ranking
players = players.sort(function(pA,pB){
return pA.ranking - pB.ranking;
});
players.forEach(function(player){
console.log(player.name,player.ranking);
});
}
main();
Try following. I am just using push of array(for adding an object to array). And for sorting you can use sort(for sorting array based on the score) of Array.Prototype. See below code.
var array=[];
function add(){
var x={};
x.name=prompt("Player " + (array.length+1) + " : ");
x.score=parseInt(prompt("Score " + (x.name) + " : "));
array.push(x);
array.sort((a,b)=>a.score<b.score)
console.log(array);
}
<button onclick="add()">add</button>
You should use array of objects instead of separate arrays like:
let data = [
{name: 'Jeremy', score: 12},
{name: 'Julien', score: 18},
{name: 'Olivia', score: 22}
];
You can then sort and print result with .sort():
let data = [
{name: 'Jeremy', score: 12},
{name: 'Julien', score: 18},
{name: 'Olivia', score: 22}
];
data.sort((a, b) => b.score - a.score);
console.log(`The first => ${data[0].name} with ${data[0].score} scores`);
console.log(`The second => ${data[1].name} with ${data[1].score} scores`);
console.log(`The third => ${data[2].name} with ${data[2].score} scores`);
However if for some reasons you want to stick with 2 arrays, you can also transform both arrays in single array of object and print result.
let players = ['Jeremy', 'Julien', 'Olivia'];
let score = [12, 18, 22];
function printResult(p, s) {
let a = p.reduce((a, c, i) => (a.push({name: c, score: s[i]}), a), [])
.sort((a, b) => b.score - a.score);
console.log(`The first => ${a[0].name} with ${a[0].score} scores`);
console.log(`The second => ${a[1].name} with ${a[1].score} scores`);
console.log(`The third => ${a[2].name} with ${a[2].score} scores`);
}
printResult(players, score);
Useful Resources:
Array.prototype.sort()
Template literals

Is it faster to loop through JavaScript objects with fewer properties?

If there are two object definitions and one of the objects has a lot more properties than the other -
Example objects:
var personObjectType1 =
{
name: [a string],
age: [an int]
};
var personObjectType2 =
{
name: [a string],
age: [an int],
address: [a string],
photo: [a link],
spouse: [a string],
cars: [an array of strings],
children: [an array of strings],
pets: [an array of strings],
father: [a string],
mother: [a string],
birthdate: [a date]
};
And you have an equal length array of each of those objects, will looping through the array of objects be faster for the objects with fewer properties?
(NOTE: The same action is being performed on each type of object)
Example code:
//personObjectType1Array is an array of 10000 personObjectType1's
//personObjectType2Array is an array of 10000 personObjectType2's
for (var i = 0; i < personObjectType1Array.length; i++)
{
console.log(personObjectType1Array[i].age);
}
for (var j = 0; j < personObjectType2Array.length; j++)
{
console.log(personObjectType2Array[i].age);
}
Would one loop run faster than the other? Why or why not?
EDIT:
Responses are saying that there is no difference, can anyone say why?
The performance is seems almost same with both the array
var personObjectType1Array = [];
var personObjectType2Array = [];
for(var i=0; i<10000; i++)
{
personObjectType1Array.push({
name: '[a string]',
age: 25
});
personObjectType2Array.push(
{
name: '[a string]',
age: 25,
address: '[a string]',
photo: '[a link]',
spouse: '[a string]',
cars: '[an array of strings]',
children: '[an array of strings]',
pets: '[an array of strings]',
father: '[a string]',
mother: '[a string]',
birthdate: '[a date]'
}
);
}
//personObjectType1Array is an array of 10000 personObjectType1's
//personObjectType2Array is an array of 10000 personObjectType2's
var startTimeArray1 = window.performance.now();
for (var i = 0; i < personObjectType1Array.length; i++)
{
//console.log(personObjectType1Array[i].age);
}
console.log('TimeArray1 : ' + (window.performance.now() - startTimeArray1));
var startTimeArray2 = window.performance.now();
for (var j = 0; j < personObjectType2Array.length; j++)
{
//console.log(personObjectType2Array[i].age);
}
console.log('TimeArray2 : ' + (window.performance.now() - startTimeArray2));
Here I have created a demo
https://jsbin.com/hurewod/edit?js,console
you can check time taken of both in console.Execution time of those having more property will be more.
var personObjectType1 =
{
name : 'xyz',
age : 12,
roll : 23,
code :29,
height :26,
address:{"streetNo":121,"City":"New Delhi"}
};
var personObjectType2 = {name : 'xyz'};
var t0 = performance.now();
for (var i = 0; i < personObjectType1.length; i++){
//console.log(personObjectType1[i].name);
}
var t1 = performance.now();
console.log("Call to personObjectType1 took " + (t1 - t0) + " milliseconds.")
var t2 = performance.now();
for (var j = 0; j < personObjectType2.length; j++){
//console.log(personObjectType2[j].name);
}
var t3 = performance.now();
console.log("Call to personObjectType2 took " + (t3 - t2) + " milliseconds.")
Probably because the code needs to be compiled the first time through. You'll get the best metrics by calling all methods first, then execute.
Incidentally, the difference in performance between loop will be negligible and the readability benefits of using loop have a marginal performance benefit.

Convert string literals in an array to variable name

I'm new to javascript. I am trying to store object variable names in an array but the way I'm doing it, the array values become strings. Is there a way to change these values from strings to the object variable names? In the following code, the last statement is what I would like to use but it generates "undefined" because, I think, it's seen as a string. Thanks!
var plan1 = {
name: "Lisa",
price: 5.00,
space: 100
}
var plan2 = {
name: "John",
price: 2.00,
space: 150
}
var myArray = [];
for (var i = 0; i < 2; i++) {
myArray[i] = "plan" + (i + 1);
}
alert(plan2.name);
alert(myArray[1].name);
Disclaimer: it's a very bad style, try to avoid it. Look at http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html
You can consider using eval:
for (var i = 0; i < 2; i++) {
myArray[i] = eval("plan" + (i + 1));
}
You can't build the name like you are trying to do and get it to store the object with the same name. What you have in myArray is the strings "plan1" and "plan2".
You would have to do something like myArray[0] = plan1; myArray[1] = plan2; Then it should work in the array like you want it to.
Don't try to do that programmatically. Just build your array literal out of the parts that you want it to contain:
var plan1 = {
name: "Lisa",
price: 5.00,
space: 100
};
var plan2 = {
name: "John",
price: 2.00,
space: 150
};
var myArray = [plan1, plan2];
Or even don't use those variables for the objects at all, and directly put them in the array structure:
var myArray = [{
name: "Lisa",
price: 5.00,
space: 100
}, {
name: "John",
price: 2.00,
space: 150
}];
you can use
myArray[i] = window["plan" + (i + 1)];
working copy at http://plnkr.co/edit/7pY4Lcmx6wN1rQk9rklu?p=preview

Subtract arrays - javascript [duplicate]

This question already has answers here:
What is the fastest or most elegant way to compute a set difference using Javascript arrays?
(14 answers)
Closed 9 years ago.
I have arrays like;
var john = { name: "John Smith", age: 23 };
var mary = { name: "Mary Key", age: 18 };
var bob = { name: "Bob-small", age: 6 };
var people = [john, mary, bob];
var john2 = { name: "John Smith", age: 23 };
var people2 = [john2];
What I would like to do is subtract people2 from people and get result;
[mary, bob];
How can I achieve this?
TIA
The difference of two sets, A and B, is defined as the set of all those elements of A which are not in B. If we implement it naively, computing the difference of two sets of sizes m and n respectively would take O(m * n) time. Not very efficient:
const john1 = { name: "John Smith", age: 23 };
const john2 = { name: "John Smith", age: 23 };
const mary = { name: "Mary Key", age: 18 };
const bob = { name: "Bob-small", age: 6 };
const people1 = [john1, mary, bob];
const people2 = [john2];
const eqPerson = (p, q) => p.name === q.name && p.age === q.age;
const result = people1.filter(p => people2.every(q => !eqPerson(p, q)));
console.log(result); // [mary, bob]
Fortunately, there's a faster way to compute the set difference for large sets using hashing.
const john1 = { name: "John Smith", age: 23 };
const john2 = { name: "John Smith", age: 23 };
const mary = { name: "Mary Key", age: 18 };
const bob = { name: "Bob-small", age: 6 };
const people1 = [john1, mary, bob];
const people2 = [john2];
const hashPerson = ({ name, age }) => `${name} ${age}`;
const hashSet = new Set(people2.map(hashPerson));
const result = people1.filter(p => !hashSet.has(hashPerson(p)));
console.log(result); // [mary, bob]
The advantage is that creating a hash set takes O(n) time and calculating the difference takes O(m) time. Hence in total it only takes O(m + n) time instead of O(m * n) time. In addition, you can reuse the hash set in the future.
Here is an easy solution:
var diff = people.filter(function(item) {
return !people2.some(function(test){
return test.name === item.name && test.age === item.age;
});
});
Make sure the function passed to people2.some correctly checks that the two objects are equal, since == would fail, as you have references to different objects with identical properties.
So, here goes the final running code. Copy , paste it and check for the output.It is first of all separating the strings (comma-separation). Then it is comparing them individually . Check this link: http://jsfiddle.net/DXRZ4/
<html>
<head>
<script>
var a = new Array(); var i=1; var people = new Array();
function fun() {
var str = "john,john,bob",
l = str.split(",");
for(i=0; i<3; i++) {
a[i] = l[i];
// this will show the comma separated strings
document.writeln(l[i]);
}
for(i=0; i<3; i++) {
t=a[i];
j=a[i+1];
if((a[i]==a[i+1]) || (a[i]==a[i+2])) {
// it will store the position of string which are same
p=i;
}
}
for(i=0; i<3; i++) {
if(p!=i){
document.writeln("Subtracted Strings are:-");
document.writeln(l[i]);
}
}
}
</script>
<body>
<input type="button" name="b1" onClick="fun()">
</body>
</html>

Categories