I am trying to display all info from an array to a table. This is my javascript array:
JS
let tableUsers = [
{name: "Jose", age: "22", Country: "Spain"},
{name: "Jon", age: "25", Country: "France"},
{name: "Jacob", age: "36", Country: "Italy"}
]
I think you are misunderstanding of variable definition.
In ES6, we use let keyword to define variable and is valid in the scope of bracket in which it is defined.
So the code should be following.
let tableUsers = document.getElementById("tableDiv");
function drawTable(){
let table = document.createElement("table");
let tableHead = document.createElement("thead");
let colHeads = ["column1", "column2"];
for (let header of colHeads){
let celle = document.createElement("th")
celle.innerHTML = header;
tableHead.appendChild(celle);
}
table.appendChild(tableHead)
let rad; // defined out of the for loop
for(let x of info){
rad = document.createElement("tr");
let firstname = document.createElement("td");
firstname.innerHTML = x.name.first;
rad.appendChild(firstname);
}
table.appendChild(rad)
}
drawTable()
Related
I am reduce an array of object into a single object that should look like this :
`
result = {
23 : [{obj of kyle}, {obj of jade}],
29 : [{obj of ruby}]
32 : [{obj of mat}]
}
`
I have used reduce to do this, each person variable will refer to an object of the array to reduce, and they all collapse into a single object refered to with the variable group, the initial value of that object is an empty object {}, so with an if statement i checked first if it's empty, then create a key named age with a new empty array as value and push the person object into that empty array, and if the key age exists, then skip the new array creation and push that corresponding person object into the corresponding array.
what's wrong with this code?
`
const people = [
{name: "kyle", age: 23},
{name: "jade", age: 23},
{name: "ruby", age: 29},
{name: "mat", age: 32}
]
let result = people.reduce(function(person, group){
const age = person.age;
if(group[age]==null){
group[age] = []
}
group[age].push(person);
return group
},{})
console.log(result);
`
not what i expected
Looking again at your code it seems that you can fix your own code by replacing person and group in your callback function inside reduce like so
const people = [
{name: "kyle", age: 23},
{name: "jade", age: 23},
{name: "ruby", age: 29},
{name: "mat", age: 32}
]
let result = people.reduce(function(group, person){
const age = person.age;
if(group[age]==null){
group[age] = []
}
group[age].push(person);
return group
},{})
console.log(result);
You can do something like this as well
const people = [
{name: "kyle", age: 23},
{name: "jade", age: 23},
{name: "ruby", age: 29},
{name: "mat", age: 32}
];
const result = people.reduce((acc, curr) => {
if (!acc[curr.age]) {
return {...acc, [curr.age]: [curr]}
}
return {...acc, [curr.age]: [...acc[curr.age], curr]};
}, {});
console.log(result);
What we did here is initiating it with a new object like you did, then for each element in the array denoted as curr for current we check if our new object (denoted as acc for accumulator) has a key with this age already of curr.age. If not we make an array for this age and put the current element inside.
Else, if this age key already exist just add to that age array the current element.
Recently started learning Swift and is now faced with the problem (code below will insert):
I create an array of structure from 3 arrays. When creating an instance of the structure, I need to do it by random (randomElement as I understood) - all 3 parameters must be unique. How do I check for uniqueness in the function?
arrayOfHumans = createRandomHuman()
struct Human {
let name: String
let surname: String
let age: String
var email: String
}
var arrayOfHumans = [Human] ()
var humans: [Human] = []
let nameA = ["Tim", "Mike", "Stan"]
let surnameA = ["Burk", "Sims", "Stoch"]
let ageA = ["12", "30", "25"]
let emailA = ["one#live.com", "two#gmail.com", "three#outlook.com"]
func createRandomHuman() -> [Human] {
for _ in 1...3 {
if nameA.isEmpty == false {
let human = Human(name: nameA.randomElement()!,
surname: surnameA.randomElement()!,
age: ageA.randomElement()!,
email: emailA.randomElement()!)
humans.append(human)
}
}
return humans
}
Actual result:
first Struct {
name: Tim
surname: Sims
age: 12
email: three#outlook.com
}
second Struct {
name: Mike
surname: Stoch
age: 25
email: one#live.com
}
third Struct {
name: Stan
surname: Burk
age: 30
email: two#gmail.com
}
A solution is to shuffle the surname, age and email arrays separately to get a random but unique order.
let nameA = ["Tim", "Mike", "Stan"]
let surnameA = ["Burk", "Sims", "Stoch"]
let ageA = ["12", "30", "25"]
let emailA = ["one#live.com", "two#gmail.com", "three#outlook.com"]
func createRandomHuman() -> [Human] {
let shuffledSurnameA = surnameA.shuffled()
let shuffledAgeA = ageA.shuffled()
let shuffledEmailA = emailA.shuffled()
var humans: [Human] = []
for i in 0..<nameA.count {
let human = Human(name: nameA[i],
surname: shuffledSurnameA[i],
age: shuffledAgeA[i],
email: shuffledEmailA[i])
humans.append(human)
}
return humans
}
let arrayOfHumans = createRandomHuman()
Another way is to shuffle the indices
func createRandomHuman() -> [Human] {
let indices = nameA.indices
let shuffledIndices = (0..<3).map{ _ in indices.shuffled()}
var humans: [Human] = []
for i in 0..<nameA.count {
let human = Human(name: nameA[i],
surname: surnameA[shuffledIndices[0][i]],
age: ageA[shuffledIndices[1][i]],
email: emailA[shuffledIndices[2][i]])
humans.append(human)
}
return humans
}
If I understand you right, you want to ensure that all randomly created humans are different.
If so, the question is when are 2 humans different. This depends on your problem. Thus you as the programmer have to define it.
You can do it by adopting the Equatable protocol.
As soon as your structs conform to this protocol, you can loop through all previously initiated humans, and check if the new randomly created one is equal to one of them. If so, create a new one.
How to assign typescript class object array by value not by reference.
Below is the code
class Person {
constructor(public Name: string, public Age: number) {
}
}
let orignalArr: Person[] = [
new Person('Gyan', 28),
new Person('Parkash', 28),
];
let arr2 = orignalArr;
//let arr2 = orignalArr.slice(0); i tried this but not working
arr2[0].Name = 'changed';
console.log(orignalArr);
//logs 0: Person {Name: "changed", Age: 28} 1: Person {Name: "Parkash", Age:
// 28}
console.log(arr2);
//logs 0: Person {Name: "changed", Age: 28} 1: Person {Name: "Parkash", Age:
// 28}
So what i need is the value of original array should not be changed.
slice will not work, because your items are also reference type and it will just return the copies of the references.
You can use map function to iterate over array items and then using Object.assign, you can copy the properties of each object into the new object.
The example is provided in Javascript.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
let originalArr = [
new Person('Gyan', 28),
new Person('Parkash', 28),
];
let arr2 = originalArr.map(item => Object.assign({}, item));
arr2[0].name = 'Changed';
console.log(originalArr[0]);
console.log(arr2[0]);
I need to mutate the following array:
struct Person {
var name: String
var age = 0
}
func showPersonArray() -> [Person] {
var dataArray = [Person]()
dataArray.append(Person(name: "Sarah_Yayvo", age: 29))
dataArray.append(Person(name: "Shanda_Lear", age: 45))
dataArray.append(Person(name: "Heidi_Clare", age: 45))
return dataArray
}
How could I split the "name"-key into two keys: "givenName" and "familyName".
Some nice person gave me this code before:
let arraySeparated1 = dataArray.map { $0.substring(to: $0.range(of: "_")!.lowerBound) }
let arraySeparated2 = dataArray.map { $0.substring(from: $0.range(of: "_")!.upperBound) }
Is it possible to make the mutation inside the struct?
The function showPersonArray() is only for demo and test.
Maybe there is a way to work with a target struct, like this:
struct Persontarget {
var familyname: String
var givenName: String
var age = 0
}
struct Person: Array -> [Persontarget] {
var name: String
var age = 0
// Here the split/mutating code
return [PersonWithTwoNames]
}
Or with an String extension. Possibly my question sounds pretty newby-like, but i´m trying the whole day...
Thanks everyone!
I would write an initializer on the new Person type, which initializes it from the old person type (which I called LegacyPerson):
import Foundation
struct LegacyPerson {
let name: String
let age: Int
}
func getPersonArray() -> [LegacyPerson] {
return [
LegacyPerson(name: "Sarah_Yayvo", age: 29),
LegacyPerson(name: "Shanda_Lear", age: 45),
LegacyPerson(name: "Heidi_Clare", age: 45)
]
}
struct Person {
let familyName: String
let givenName: String
let age: Int
}
extension Person {
init(fromLegacyPerson person: LegacyPerson) {
let index = person.name.range(of: "_")!
self.init(
familyName: person.name.substring(from: index.upperBound),
givenName: person.name.substring(to: index.lowerBound),
age: person.age
)
}
}
let people: [Person] = getPersonArray().map(Person.init)
people.forEach{ print($0) }
Create a method or computer variable for your Person class that returns what you want.
func firstName() -> String {
return self.substring(to: $0.range(of: "_")!.lowerBound)
}
You should not force cast though
with help of computed property defined in an extension
struct Person {
let name: String
let age: Int
}
let person = Person(name: "Maria_Terezia", age: 300)
extension Person {
var names:[String] {
get {
return name.characters.split(separator: "_").map(String.init)
}
}
}
for name in person.names {
print(name)
}
prints
Maria
Terezia
I want to create a new nested array with the name of a variable. Is this possible?
data example:
[{
varname {
name: person1name;
events : [{
firstName: person1name,
name: event1name,
date: date1
},{
firstName: person2name,
name: event2name,
date: date2
}
]
}
}]
code:
$scope.multiEvents = []
var eventCategory = $scope.event.name
$scope.multiEvents.eventCategory.name = $scope.event.firstName;
$scope.multiEvents.eventCategory.events.push($scope.event);
$scope.multiEvents.eventCategory.events.push($scope.event2);
Ended up doing this:
$scope.multiEvents = [];
$scope.multiEvent = {};
$scope.multiEvent.events = [];
$scope.multiEvent.name = $scope.event.firstName;
$scope.multiEvent.events.push($scope.event);
$scope.multiEvent.events.push($scope.event2);
$scope.multiEvents.push($scope.multiEvent);
I think I was just confused.