Related
I am traying to populate an array "array1" with objects with format {a:'value', b:'value'} that come from a greater objet "objPractice", (could be a json). I don't know what I am doing wrong but I get an array with objects all equals corresponding just with the last element of the original object. I need all of them, not just the last one.
This is the code:
let objPractice = {
books: [
{
isbn: "9781449325862",
title: "Git Pocket Guide",
subtitle: "A Working Introduction",
author: "Richard E. Silverman",
publish_date: "2020-06-04T08:48:39.000Z",
publisher: "O'Reilly Media",
pages: 234,
description: "This pocket guide is the perfect on-the-job companion to Git, the distributed version control system. It provides a compact, readable introduction to Git for new users, as well as a reference to common commands and procedures for those of you with Git exp",
website: "http://chimera.labs.oreilly.com/books/1230000000561/index.html"
},
{
isbn: "9781449331818",
title: "Learning JavaScript Design Patterns",
subtitle: "A JavaScript and jQuery Developer's Guide",
author: "Addy Osmani",
publish_date: "2020-06-04T09:11:40.000Z",
publisher: "O'Reilly Media",
pages: 254,
description: "With Learning JavaScript Design Patterns, you'll learn how to write beautiful, structured, and maintainable JavaScript by applying classical and modern design patterns to the language. If you want to keep your code efficient, more manageable, and up-to-da",
website: "http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/"
},
{
isbn: "9781449337711",
title: "Designing Evolvable Web APIs with ASP.NET",
subtitle: "Harnessing the Power of the Web",
author: "Glenn Block et al.",
publish_date: "2020-06-04T09:12:43.000Z",
publisher: "O'Reilly Media",
pages: 238,
description: "Design and build Web APIs for a broad range of clients—including browsers and mobile devices—that can adapt to change over time. This practical, hands-on guide takes you through the theory and tools you need to build evolvable HTTP services with Microsoft",
website: "http://chimera.labs.oreilly.com/books/1234000001708/index.html"
},
{
isbn: "9781449365035",
title: "Speaking JavaScript",
subtitle: "An In-Depth Guide for Programmers",
author: "Axel Rauschmayer",
publish_date: "2014-02-01T00:00:00.000Z",
publisher: "O'Reilly Media",
pages: 460,
description: "Like it or not, JavaScript is everywhere these days-from browser to server to mobile-and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who o",
website: "http://speakingjs.com/"
},
{
isbn: "9781491904244",
title: "You Don't Know JS",
subtitle: "ES6 & Beyond",
author: "Kyle Simpson",
publish_date: "2015-12-27T00:00:00.000Z",
publisher: "O'Reilly Media",
pages: 278,
description: "No matter how much experience you have with JavaScript, odds are you don’t fully understand the language. As part of the \\\"You Don’t Know JS\\\" series, this compact guide focuses on new features available in ECMAScript 6 (ES6), the latest version of the st",
website: "https://github.com/getify/You-Dont-Know-JS/tree/master/es6%20&%20beyond"
},
{
isbn: "9781491950296",
title: "Programming JavaScript Applications",
subtitle: "Robust Web Architecture with Node, HTML5, and Modern JS Libraries",
author: "Eric Elliott",
publish_date: "2014-07-01T00:00:00.000Z",
publisher: "O'Reilly Media",
pages: 254,
description: "Take advantage of JavaScript's power to build robust web-scale or enterprise applications that are easy to extend and maintain. By applying the design patterns outlined in this practical book, experienced JavaScript developers will learn how to write flex",
website: "http://chimera.labs.oreilly.com/books/1234000000262/index.html"
},
{
isbn: "9781593275846",
title: "Eloquent JavaScript, Second Edition",
subtitle: "A Modern Introduction to Programming",
author: "Marijn Haverbeke",
publish_date: "2014-12-14T00:00:00.000Z",
publisher: "No Starch Press",
pages: 472,
description: "JavaScript lies at the heart of almost every modern web application, from social apps to the newest browser-based games. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale ",
website: "http://eloquentjavascript.net/"
},
{
isbn: "9781593277574",
title: "Understanding ECMAScript 6",
subtitle: "The Definitive Guide for JavaScript Developers",
author: "Nicholas C. Zakas",
publish_date: "2016-09-03T00:00:00.000Z",
publisher: "No Starch Press",
pages: 352,
description: "ECMAScript 6 represents the biggest update to the core of JavaScript in the history of the language. In Understanding ECMAScript 6, expert developer Nicholas C. Zakas provides a complete guide to the object types, syntax, and other exciting changes that E",
website: "https://leanpub.com/understandinges6/read"
}
]}
And here is the code to populate the new array "array1"
let obj1 = { isbn: "", title: "" }
let array1 = []
for (var i=0; i < objPractica.books.length - 1; i++) {
obj1.isbn = objPractica.books[i].isbn
obj1.title = objPractica.books[i].title
array1.push(obj1)
}
console.log("The array [] that contains object with format {a:'value', b:'value'} is: ", array1)
But these is the result that I am getting:
The array [] that contains object with format {a:'value', b:'value'} is: [
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
},
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
},
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
},
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
},
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
},
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
},
{
isbn: '9781593275846',
title: 'Eloquent JavaScript, Second Edition'
}
]
As you can see, I just get only the last element from the original object. Why is that?
This is a fun learning experience about object references (see this article for some short reading). Follow my comments in this code snippet:
// You are creating an object here:
let obj1 = { isbn: "", title: "" }
let array1 = []
for (var i=0; i < objPractice.books.length - 1; i++) {
// You are changing properties on the _existing_ object "obj1" here:
obj1.isbn = objPractice.books[i].isbn
obj1.title = objPractice.books[i].title
// You are pushing another copy of "obj1" into the array.
array1.push(obj1)
}
You are not creating a new object in each iteration of your for loop. You are just changing the properties on the existing object (obj1) and adding another copy of it to your array.
How about this:
for (var i=0; i < objPractice.books.length - 1; i++) {
array1.push({
isbn: objPractice.books[i].isbn,
title: objPractice.books[i].title
})
}
or even better still, use some of the helpful Array prototype methods like map to make this even simpler:
const array1 = objPractice.books.map(book => ({
isbn: book.isbn,
title: book.title
}))
Here's my code.
I have a movies related tab and when a specific movie is open in a browser, under the related tab, related movies should be there. I have the map functions ready which load all the movies I have in the map object. Wanted an if and else statement to pick the same genre of movies by using a getElementId to get the id genre of the current movie and compare it with the genre in the map objects. Hope am using the right terms
//create test div
const data = [{
name: "13 reasons why",
href: "13 reasons why.php",
img: "https://images.theconversation.com/files/170594/original/file-20170523-5763-161mnda.jpg",
describe: "Newcomer Katherine Langford plays the role of Hannah, a young woman who takes her own life. Two weeks after her tragic death, a classmate named Clay finds a mysterious box on his porch. Inside the box are recordings made by Hannah -- on whom Clay had a crush -- in which she explains the 13 reasons why she chose to commit suicide. If Clay decides to listen to the recordings, he will find out if and how he made the list. This intricate and heart-wrenching tale is told through Clay and Hannah's dual narratives.",
rate: "7.6",
date: "(2017 - 2020)"
}, {
name: "30 Coins",
href: "30 coins.php",
img: "https://www.themoviedb.org/t/p/w500/b2i9aaV6ncULl9jYXEoPi7VFJg8.jpg",
describe: "Father Vergara, an exorcist, boxer and ex-convict exiled to a remote town in Spain, enlists the help of the mayor and a veterinarian when a series of paranormal phenomena begins to occur.",
rate: "7.2",
date: "(2020 - Present)"
}, {
name: "911 Lone Star",
href: "911 lone star.php",
img: "https://m.media-amazon.com/images/I/717AkBpHNjL._AC_SY450_.jpg",
describe: "9-1-1: Lone Star follows a sophisticated New York firefighter who, along with his son, relocates from Manhattan to Austin, Texas. He must try to balance the duties of saving those who are at their most vulnerable and solving the problems in his own life. ",
rate: "6.8",
date: "(2017 - 2021)"
}, {
name: "911",
href: "911.php",
img: "https://m.media-amazon.com/images/M/MV5BMzNiMmNmZWQtMTJlMS00NWIyLTlhNmEtNmI3M2Q1YjczMGI4XkEyXkFqcGdeQXVyNjEwNTM2Mzc#._V1_.jpg",
describe: "Policemen, paramedics and firefighters put themselves in dangerous situations to save people's lives. Meanwhile, they also have to deal with their personal problems.",
rate: "7.6",
date: "(2018 - Present)"
}, {
name: "A confession",
href: "a confession.php",
img: "https://m.media-amazon.com/images/M/MV5BZTc0ZjQxOWEtNTc4MS00ZjgxLThkOWEtZGM1NzgzOWYwOTc1XkEyXkFqcGdeQXVyMTAyNjU1NjU5._V1_.jpg",
describe: "The true story of DS Stephen Fulcher and his hunt for missing 22-year-old Sian O'Callaghan, and how it lead to the arrest of Christopher Halliwell. This was the beginning of the capture of a prolific serial killer and the detectives own downfall.",
rate: "7.6",
date: "(2019)"
}, {
name: "A million little things",
href: "a million little things.php",
img: "http://www.gstatic.com/tv/thumb/tvbanners/17114373/p17114373_b_v12_aa.jpg",
describe: "The lives of a group of carefree friends from Boston change when one of them shockingly dies. They soon realise the importance of cherishing their friendship.",
rate: "7.9",
date: "(2018)"
}, {
name: "A teacher",
href: "a teacher.php",
img: "https://m.media-amazon.com/images/M/MV5BZjgzMmUwZjgtNzNhMi00M2Y0LWIxOTAtYzYzODdjMTYzZWQyXkEyXkFqcGdeQXVyMTIwNDUyNzMy._V1_.jpg",
describe: "This drama series examines the complexities and consequences of an illicit sexual affair between a young teacher and her student. Claire is a new teacher at Westerbrook High School in Texas. Dissatisfied in her marriage to her college sweetheart, Claire's life changes when Eric, a personable teenager in her English class, takes an interest in her. Popular and outgoing, Eric is the captain of the soccer team and nearly inseparable from his best friends. Everything seems perfect on the surface, but Eric is forced to juggle the pressures of school, applying for college and a part-time job, all while helping take care of his two younger brothers. Claire and Eric discover an undeniable connection that allows them to escape their lives, but their relationship accelerates faster than either could anticipate. The permanent damage left in the wake of their illicit affair becomes impossible for them, and their friends and family, to ignore.",
rate: "6.9",
date: "(2020)"
}, {
name: "Absentia",
href: "absentia.php",
img: "https://m.media-amazon.com/images/M/MV5BNmFiNDI5ODUtODQ2ZC00ZjUwLWFhYjQtMjk3MmMzZjY1ZWU2XkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_.jpg",
describe: ">Six years after going missing and being declared dead, FBI agent Emily Byrne is found alive in a cabin in the woods. With no memory of her past, she sets out to reclaim her life and identity.",
rate: "7.3",
date: "(2017 - 2020)"
}, {
name: "After Life",
href: "after life.php",
img: "https://m.media-amazon.com/images/M/MV5BZjdjOWIxMDgtYTgwNS00MjE4LTliZWYtZGI1NDhhZmIyYjM1XkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_.jpg",
describe: "Tony had a perfect life -- until his wife Lisa died. After that tragic event, the formerly nice guy changed. After contemplating taking his life, Tony decides he would rather live long enough to punish the world by saying and doing whatever he likes. He thinks of it as a superpower -- not caring about himself or anybody else -- but it ends up being trickier than he envisioned when his friends and family try to save the nice guy that they used to know. Golden Globe winner Ricky Gervais stars in the comedy series, which he also writes and directs.",
rate: "8.4",
date: "(2019 - 2020)"
}, {
name: "Alex Rider",
href: "alex rider.php",
img: "https://m.media-amazon.com/images/M/MV5BOTg4ZmQ5ZjItZTllZC00NzUzLTkwMTEtMjIzYzliZjk2ODUwXkEyXkFqcGdeQXVyMTEyMjM2NDc2._V1_.jpg",
describe: "London teenager Alex Rider is recruited by the Department of Special Operations, a subdivision of the Secret Intelligence Service (MI6), to infiltrate a controversial corrective academy for the wayward offspring of the ultra-rich.",
rate: "7.6",
date: "(2020)"
}, {
name: "All Rise",
href: "all rise.php",
img: "https://m.media-amazon.com/images/M/MV5BYTk5ZjI0M2MtYjQ5Ny00OWJmLWExYWEtNjRlMTdkNjYwMGIzXkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_.jpg",
describe: "A look inside the chaotic, hopeful and sometimes absurd lives of judges, prosecutors and public defenders as they work with bailiffs, clerks and cops to get justice for the people of Los Angeles amidst a flawed legal process. Among them is newly appointed Judge Lola Carmichael, a highly regarded and impressive deputy district attorney who doesn't intend to sit back on the bench in her new role, but instead leans in, immediately pushing the boundaries and challenging the expectations of what a judge can be.",
rate: "6.7",
date: "(2019 - 2021)"
}, {
name: "Altered Carbon",
href: "altered carbon.php",
img: "https://m.media-amazon.com/images/M/MV5BNjIxMWMzMzctYmZkYy00OTkzLWFlMWUtMjc3ZDFmYzQ3YmVkXkEyXkFqcGdeQXVyNjU2ODM5MjU#._V1_.jpg",
describe: "More than 300 years in the future, society has been transformed by new technology, leading to human bodies being interchangeable and death no longer being permanent. Takeshi Kovacs is the only surviving soldier of a group of elite interstellar warriors who were defeated in an uprising against the new world order. His mind was imprisoned for centuries until impossibly wealthy businessman Laurens Bancroft offers him the chance to live again. Kovacs will have to do something for Bancroft, though, if he wants to be resurrected. Bancroft's request of Kovacs is to solve a murder Bancroft's. 'Altered Carbon' is based on Richard K. Morgan's cyberpunk noir novel of the same name.",
rate: "8",
date: "(2018 - 2020)"
}, {
name: "American Horror Story",
href: "american horror story.php",
img: "https://flxt.tmsimg.com/assets/p9423798_b_v12_ad.jpg",
describe: "An anthology series centering on different characters and locations, including a house with a murderous past, an insane asylum, a witch coven, a freak show circus, a haunted hotel, a possessed farmhouse, a cult, the apocalypse, a slasher summer camp, and a bleak beach town and desert valley.",
rate: "7.6",
date: "(2011 - Present)"
}, {
name: "Anne With An E",
href: "anne with an e.php",
img: "https://m.media-amazon.com/images/M/MV5BNThmMzJlNzgtYmY5ZC00MDllLThmZTMtNTRiMjQwNmY0NmRhXkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_FMjpg_UX1000_.jpg",
describe: "This reimagining of the classic book and film is a coming-of-age story about a young orphan who is seeking love, acceptance and her place in the world. Amybeth McNulty stars as Anne, a 13-year-old who has endured an abusive childhood in orphanages and the homes of strangers. In the late 1890s, Anne is mistakenly sent to live with aging siblings, Marilla and Matthew Cuthbert, who live on Prince Edward Island. Anne, who proves to be uniquely spirited, imaginative and smart, transforms the lives of Marilla, Matthew and everyone else in their small town.",
rate: "8.7",
date: "(2017 - 2019)"
}, {
name: "animal kingdom",
href: "animal kingdom.php",
genre: "drama",
img: "https://m.media-amazon.com/images/M/MV5BOTk1NjAwOTM1OV5BMl5BanBnXkFtZTgwMzUwODQ3NzM#._V1_FMjpg_UX1000_.jpg",
describe: "After the death of his mother, Joshua decides to live with his grandmother, who heads a criminal clan. His life takes a turn as he gets involved with his cousins and their criminal activities.",
rate: "8.2",
date: "(2016 - Present)"
}, {
name: "Arrow",
href: "arrow.php",
genre: "drama",
img: "https://m.media-amazon.com/images/M/MV5BMTI0NTMwMDgtYTMzZC00YmJhLTg4NzMtMTc1NjI4MWY4NmQ4XkEyXkFqcGdeQXVyNTY3MTYzOTA#._V1_.jpg",
describe: "After mastering the skill of archery on a deserted island, multi-millionaire playboy Oliver Queen returns to his city to take on the vigilante persona of Arrow to fight crime and corruption.",
rate: "7.5",
date: "(2012 - 2020)"
}, {
name: "Atypical",
href: "atypical.php",
img: "https://m.media-amazon.com/images/M/MV5BMjNjNThmYTUtMjY2Ni00OGE4LTgzOTItYTgzMDllNDM5NTI5XkEyXkFqcGdeQXVyNjEwNTM2Mzc#._V1_FMjpg_UX1000_.jpg",
describe: "This heartfelt comedy follows Sam, a teenager on the autism spectrum, who has decided he is ready for romance. In order to start dating -- and hopefully find love -- Sam will need to be more independent, which also sends his mother (Jennifer Jason Leigh) on her own life-changing path. She and the rest of Sam's family, including a scrappy sister and a father seeking a better understanding of his son, must adjust to change and explore what it means to be normal. The series is created and written by Robia Rashid and Academy Award-winning producer Seth Gordon.",
rate: "8.3",
date: "(2017 - 2021)"
}]
const createTest = (selector) => {
const test = document.querySelector(selector)
console.log(selector)
let html = ''
data.map(({
id,
name,
href,
img,
describe,
rate,
date
}, index) => {
html = `
${html}
<div class="movie-item-style-2">
<div id="product${index}" class="mv-item-infor">
<img src="${img}" alt="">
<h6 style="padding-top: 1em;">${name} <span>${date}</span></h6>
<p class="rate"><i class="ion-android-star"></i><span>${rate}</span> /10</p>
<p class="describe">${describe}</p>
</div>
</div>
`
})
test.innerHTML = html
}
createTest(".content")
<div id="moviesrelated" class="tab">
<div class="row">
<h3>Related Movies</h3>
<div class="test"></div>
<div class="topbar-filter">
<p>Found <span>12 movies</span> in total</p>
<label>Sort by:</label>
<select>
<option value="popularity">Popularity Descending</option>
<option value="popularity">Popularity Ascending</option>
<option value="rating">Rating Descending</option>
<option value="rating">Rating Ascending</option>
<option value="date">Release date Descending</option>
<option value="date">Release date Ascending</option>
</select>
</div>
<div class="content">
</div>
<div class="topbar-filter">
<label>Movies per page:</label>
<select>
<option value="range">5 Movies</option>
<option value="saab">10 Movies</option>
</select>
<div class="pagination2">
<span>Page 1 of 2:</span>
<a class="active" href="#">1</a>
2
<i class="ion-arrow-right-b"></i>
</div>
</div>
</div>
</div>
I am trying to learn/use Node and Javascript by re-coding a PHP/MYSQL application I made that is not very efficient - as I built it while I was trying to earn those technologies as well.
I am trying to re-use a some of the information that is created or stored in JSON format.
I have in one file a set of 52 questions that looks like such...
//questions.json
{
"School" : {
"Question 1": "The facilities of the school adequately provide for a positive learning/working experience.",
"Question 2": "School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.",
"Question 3": "School is well funded to provide students and faculty with adequate materials to support their course offering.",
"Question 4": "Parent community is actively involved in supporting the school's mission and their child's education endeavors.",
"Question 5": "Classroom student to teacher ratios are kept low."
},
"Students" : {
"Question 6": "Students are generally of high aptitude.",
"Question 7": "Student interactions with faculty are primarily characterized by respectability.",
"Question 8": "Students are of diverse ethnicity."
},
"Administration" : {
"Question 9": "Administration positively supports faculty in a professional manner.",
"Question 10": "Administration actively encourages a dialogue concerning school related issues.",
"Question 11": "Administration is actively engaged in developing/supporting/maintaining a clear school vision.",
"Question 12": "Administration makes sure that the financial stability and integrity of the school is well maintained.",
"Question 13": "Administration/Ownership uses school funds to support the well being of the school."
},...
I also have a Knex script that does a query on the data and returns an array like below....
[ { Q1: 8.44,
Q2: 9.13,
Q3: 8.81,
Q4: 8.38,
Q5: 7.63,
Q6: 8.06,
Q7: 8.56,
Q8: 8.5,
Q9: 7.63,
Q10: 8.13,
Q11: 8.5,
Q12: 8.88,
Q13: 8.75,
Q14: 7.38,
Q15: 8.13,
Q16: 8.56,...
I would like to try to combine these two arrays to look like...
{
"School" : {
{"Question 1" : {
"Question" : "The facilities of the school adequately provide for a positive learning/working experience.",
"Average" : 8.44
},
{"Question 2" : {
"Question" : ""School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc."",
"Average" : 9.13
}
If need be I can remove the category divisions within the .json file if that make combining easier, but in the end applications I display the data in sections, so I will eventually filter it. I just thought maybe dividing it in the json file would make it easier.
I am able to concat the arrays, and I have looked at .map but I am not sure how I would apply it to this. It looks like I would need a nested loop?
Using a double forEach loop:
const questions = {
"School" : {
"Question 1": "The facilities of the school adequately provide for a positive learning/working experience.",
"Question 2": "School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.",
"Question 3": "School is well funded to provide students and faculty with adequate materials to support their course offering.",
"Question 4": "Parent community is actively involved in supporting the school's mission and their child's education endeavors.",
"Question 5": "Classroom student to teacher ratios are kept low."
},
"Students" : {
"Question 6": "Students are generally of high aptitude.",
"Question 7": "Student interactions with faculty are primarily characterized by respectability.",
"Question 8": "Students are of diverse ethnicity."
}
};
const scores = {
Q1: 8.44,
Q2: 9.13,
Q3: 8.81,
Q4: 8.38,
Q5: 7.63,
Q6: 8.06,
Q7: 8.56,
Q8: 8.5
};
// Placeholder for your result
const result = {};
// Iterate through the question categories:
const categories = Object.keys(questions);
categories.forEach(cat => {
// Add category to result
result[cat] = {};
// Get the question keys for that category
const questionKeys = Object.keys(questions[cat]);
questionKeys.forEach(q => {
// Get the score key. i.e: Question 1 -> Q1
const scoreKey = q.replace('Question ', 'Q');
// Add question to result
result[cat][q] = {
Question: questions[cat][q],
Average: scores[scoreKey]
};
});
});
console.log(result);
What I do below is basically:
I take the question number out of "Question 1"
Combine it with "Q" to get "Q1"
And then the plain old key lookup in the object you have based on this new string.
All this, in loops below
var newObj = {};
// replace /*questions.json*/ with your actual object.
for (var category in /*questions.json*/){
var questionsObj = /*questions.json*/[category];
newObj[category] = {}
for (var question in questionsObj) {
newObj[category][question] = {};
newObj[category][question].question = questionsObj[question];
var qNumber = question.split("Question ")[1];
newObj[category][question].Average = dataArray[0]["Q"+qNumber];
}
}
I am using Angular with Typescript. I have array of objects with multiple properties. I have grouped them in server side code and set duplicate property. When user updates the list I have to loop though the list and find duplicates in the client side. Is there any C# LINQ GroupBy equivalent in Typescript?
Here is my C# LINQ code:
listMP.Where(item => item.Type == "Other").GroupBy(i => new { i.Type, i.Name, i.Address1, i.City }).Where(g => g.Count() > 1)
.SelectMany(g=>g.Select(gg =>gg.Id));
Such an old question, yet a plain typescript answer is not yet given imho.
This is how a groupBy is done in typescript with reduce:
const grouped = myArray
.reduce(
(g: { [id: string]: MyObject[] }, o: MyObject) => {
g[o.FK] = g[p.FK] || []; //check if key allready exists, else init a new array
g[o.FK].push(o); //add item to array
return g; // be sure to return, or g will be undefined in next loop
},
{} //a second parameter to the reduce function, important to init the returned object
);
What is the Typescript equivalent to C# LINQ GroupBy ?
You can use Array.prototype.reduce : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Alternatively you can use lodash groupBy: https://lodash.com/docs/4.17.4#groupBy
There is a TypeScript library for LINQ.
It is called ts-generic-collections-linq.
Providing strongly-typed, queryable collections such as:
List
Dictionary
Easy to use.
NPM
https://www.npmjs.com/package/ts-generic-collections-linq
Sample linq query:
//query to get owners by the sex/gender of their pets
let ownersByPetSex = owners.join(pets, owner => owner.id, pet => pet.ownerId, (x, y) => new OwnerPet(x,y))
.groupBy(x => [x.pet.sex])
.select(x => new OwnersByPetSex(x.groups[0], x.list.select(x => x.owner)));
I am working with a small 'Linq-like' library written in Typescript that can be used with arrays and Angular 8 or newer in a hobby project of mine. (Not recommended for commercial use yet, but it could inspire others to make a fully grown Linq like library for Typescript perhaps).
Array-extensions.ts on Github
It is possible to pass in a grouping function, so you can define how you want to group your array of objects of multiple properties. Here is how I did it with Angular 8 and Typescript.
First off, define in a file array-extensions.ts this:
export { } //creating a module of below code
declare global {
type predicate<T> = (arg: T) => boolean;
type sortingValue<T> = (arg: T) => any;
interface Array<T> {
GroupBy<T>(groupFunc: (arg: T) => string): any[];
}
}
if (!Array.prototype.GroupBy) {
Array.prototype.GroupBy = function <T>(groupFunc: (arg: T) => string): any[] {
let groups: any = {};
this.forEach(el => {
let itemKeyValue: any = groupFunc(el);
if (itemKeyValue in groups === false) {
groups[itemKeyValue] = [];
}
groups[itemKeyValue].push(el);
});
let result = Object.keys(groups).map(key => {
return {
key: key,
values: groups[key]
}
});
return result;
}
}
We can now group our array of objects like this in say a constructor of a component for example.
this.groupedMoviesWithJarJarBinks = StarWarsMovies.GroupBy<Movie>(movie =>
movie.main_characters.indexOf('Jar Jar Binks') >= 0 ? "Movie starring JarJar" : "Movie not starring JarJar");
Here is some sample data:
import { Movie } from './movie';
export const StarWarsMovies : Array<Movie> =
[{
"title" : "Star Wars: Episode I - The Phantom Menace",
"episode_number" : "1",
"main_characters" : ["Qui-Gon Jinn", "Obi-Wan Kenobi", "Anakin Skywalker", "Padmé Amidala", "Jar Jar Binks", "Darth Maul"],
"description" : "The evil Trade Federation, led by Nute Gunray is planning to take over the peaceful world of Naboo. Jedi Knights Qui-Gon Jinn and Obi-Wan Kenobi are sent to confront the leaders. But not everything goes to plan. The two Jedi escape, and along with their new Gungan friend, Jar Jar Binks head to Naboo to warn Queen Amidala, but droids have already started to capture Naboo and the Queen is not safe there. Eventually, they land on Tatooine, where they become friends with a young boy known as Anakin Skywalker. Qui-Gon is curious about the boy, and sees a bright future for him. The group must now find a way of getting to Coruscant and to finally solve this trade dispute, but there is someone else hiding in the shadows. Are the Sith really extinct? Is the Queen really who she says she is? And what's so special about this young boy?",
"poster" : "star_wars_episode_1_poster.png",
"hero_image" : "star_wars_episode_1_hero.jpg"
},
{
"title" : "Star Wars: Episode II - Attack of the Clones",
"episode_number" : "2",
"main_characters" : ["Obi-Wan Kenobi", "Anakin Skywalker", "Count Dooku", "Padmé Amidala", "Mace Windu", "Yoda", "Jango Fett", "Supreme Chancellor Palpatine"],
"description" : "Ten years after the 'Phantom Menace' threatened the planet Naboo, Padmé Amidala is now a Senator representing her homeworld. A faction of political separatists, led by Count Dooku, attempts to assassinate her. There are not enough Jedi to defend the Republic against the threat, so Chancellor Palpatine enlists the aid of Jango Fett, who promises that his army of clones will handle the situation. Meanwhile, Obi-Wan Kenobi continues to train the young Jedi Anakin Skywalker, who fears that the Jedi code will forbid his growing romance with Amidala.",
"poster" : "star_wars_episode_2_poster.png",
"hero_image" : "star_wars_episode_2_hero.jpg"
},
{
"title" : "Star Wars: Episode III - Revenge of the Sith",
"episode_number" : "3",
"main_characters" : ["Obi-Wan Kenobi", "Anakin Skywalker", "Count Dooku", "Padmé Amidala", "Mace Windu", "Yoda", "C-3PO", "Supreme Chancellor Palpatine"],
"description" : "Three years after the onset of the Clone Wars; the noble Jedi Knights are spread out across the galaxy leading a massive clone army in the war against the Separatists. After Chancellor Palpatine is kidnapped, Jedi Master Obi-Wan Kenobi and his former Padawan, Anakin Skywalker, are dispatched to eliminate the evil General Grievous. Meanwhile, Anakin's friendship with the Chancellor arouses suspicion in the Jedi Order, and dangerous to the Jedi Knight himself. When the sinister Sith Lord, Darth Sidious, unveils a plot to take over the galaxy, the fate of Anakin, the Jedi order, and the entire galaxy is at stake. Upon his return, Anakin Skywalker's wife Padme Amidala is pregnant, but he is having visions of her dying in childbirth. Anakin Skywalker ultimately turns his back on the Jedi, thus completing his journey to the dark side and his transformation into Darth Vader. Obi-Wan Kenobi must face his former apprentice in a ferocious lightsaber duel on the fiery world of Mustafar.",
"poster" : "star_wars_episode_3_poster.png",
"hero_image" : "star_wars_episode_3_hero.jpg"
},
{
"title" : "Star Wars: Episode IV - A New Hope",
"episode_number" : "4",
"main_characters" : ["Luke Skywalker", "Han Solo", "Princess Leia Organa", "Ben Kenobi", "Darth Vader", "C-3P0", "R2-D2", "Chewbacca"],
"description" : "Part IV in George Lucas' epic, Star Wars: A New Hope opens with a Rebel ship being boarded by the tyrannical Darth Vader. The plot then follows the life of a simple farm boy, Luke Skywalker, as he and his newly met allies (Han Solo, Chewbacca, Obi-Wan Kenobi, C-3PO, R2-D2) attempt to rescue a Rebel leader, Princess Leia, from the clutches of the Empire. The conclusion is culminated as the Rebels, including Skywalker and flying ace Wedge Antilles make an attack on the Empire's most powerful and ominous weapon, the Death Star.",
"poster" : "star_wars_episode_4_poster.png",
"hero_image" : "star_wars_episode_4_hero.jpg"
},
{
"title" : "Star Wars: Episode V - The Empire Strikes Back",
"episode_number" : "5",
"main_characters" : ["Luke Skywalker", "Han Solo", "Princess Leia Organa", "Darth Vader", "C-3P0", "R2-D2", "Chewbacca", "Lando Calrissian", "Boba Fett"],
"description" : "Fleeing the evil Galactic Empire, the Rebels abandon their new base in an assault with the Imperial AT-AT walkers on the ice world of Hoth. Princess Leia, Han Solo, Chewbacca and the droid C-3PO escape in the Millennium Falcon, but are later captured by Darth Vader on Bespin. Meanwhile, Luke Skywalker and the droid R2-D2 follows Obi-Wan Kenobi's posthumous command, and receives Jedi training from Master Yoda on the swamp world of Dagobah. Will Skywalker manage to rescue his friends from the Dark Lord?",
"poster" : "star_wars_episode_5_poster.png",
"hero_image" : "star_wars_episode_5_hero.jpg"
},
{
"title" : "Star Wars: Episode VI - Return of the Jedi",
"episode_number" : "6",
"main_characters" : ["Luke Skywalker", "Han Solo", "Princess Leia Organa", "Darth Vader", "C-3P0", "Chewbacca", "The Emperor", "Boba Fett"],
"description" : "Darth Vader and the Empire are building a new, indestructible Death Star. Meanwhile, Han Solo has been imprisoned, and Luke Skywalker has sent R2-D2 and C-3PO to try and free him. Princess Leia - disguised as a bounty hunter - and Chewbacca go along as well. The final battle takes place on the moon of Endor, with its natural inhabitants, the Ewoks, lending a hand to the Rebels. Will Darth Vader and the Dark Side overcome the Rebels and take over the universe?",
"poster" : "star_wars_episode_6_poster.png",
"hero_image" : "star_wars_episode_6_hero.jpg"
}];
Movie class looks like this:
export class Movie {
title: string;
episode_number: string;
main_characters: string[];
description: string;
poster: string;
hero_image: string;
}
This allows us to group arrays using Typescript with a syntax very similar to that of C# and Linq.
I have created a new and modern TypeScript LINQ library named sharp-collections. It supports all of .NET LINQ methods and some more (including groupBy). It has features like defferred (lazy) execution, ForOf cycle compatibility etc. More info here: https://github.com/vdolek/sharp-collections.
import { Enumerable } from 'sharp-collections';
const data = [
{ name: 'Martin', sex: 'M', age: 28 },
{ name: 'Jane', sex: 'F', age: 27 },
{ name: 'Thomas', sex: 'M', age: 15 },
{ name: 'William', sex: 'M', age: 78 },
{ name: 'Kelly', sex: 'F', age: 30 },
];
const enumerable = Enumerable.from(data); // or List.from(data)
const adults = enumerable.where(x => x.age >= 18);
const adultsGroupedBySex = adults.groupBy(x => x.sex); // nothing is executed so far
// use any collection (Enumerable, List, ...) in ForOf cycle
for (const group of adultsGroupedBySex) {
console.debug(`Sex: ${group.key}, count: ${group.count()}`);
}
// converts Enumerable to List
const adultsGroupedBySexList = adultsGroupedBySex.toList(); // or toReadOnlyList()
// converts Enumerable to JS Array
const adultsGroupedBySexArray = adultsGroupedBySex.toArray();
I am new at learning code - so please be patient. I am attempting to create a Jeopardy style game for my wife (who is a school teacher). However, I am running into a problem. I would like to click on a link ($100, etc.) and have the clue (value) logged into a div on a separate page. Through my research, I have settled on creating a JSON object from an array and then have the JSON parsed for index and value.
Here is my HTML:
<ul id="rowOne">
<li>$100</li>
<li>$100</li>
<li>$100</li>
<li>$100</li>
<li>$100</li>
</ul>
Here is the div where I would like the value logged:
<div id="clueContainer" class="center"></div>
Here is my Jquery:
$(document).ready(function(){
var rowOne = array [
{name:"$100", value:"On the world political map, where were some of the major states and empires located about 1500 A.D. (C.E.)?"},
{name:"$200", value:"What were the artistic, literary, and intellectual ideas of the Renaissance?"},
{name:"$300", value:"Where were the five world religions located around 1500 A.D. (C.E.)?"},
{name:"$400", value:"What were the regional trading patterns about 1500 A.D. (C.E.)?"},
{name:"$500", value:"Why were the regional trading patterns important?",}
];
var json = JSON.parse(rowOne);
$("li a href").click(function(){
$.each(json, function(index, value){
$("#clueContainer").append(function(){
$(value).log(<p>+value+</p>);
});
});
});
});
Are there any ideas out there or an I approaching this project the wrong way?
You have the right idea for arrays but the syntax is a little different than what you have. I've created an array of array of objects. The structure is similar to this:
var arr = [[
{
property: value
}, {
property: value
}][{
property: value
}, {
property: value
}]
];
I added a class called rows to the ul element and you can then iterate over that with each() using jQuery's built in index (p in our case) and then iterate over the number of a elements in the ul to add a question from the rows array.
$(document).ready(function () {
var rows = [
[{
name: "$100",
value: "On the world political map, where were some of the major states and empires located about 1500 A.D. (C.E.)?"
}, {
name: "$200",
value: "What were the artistic, literary, and intellectual ideas of the Renaissance?"
}, {
name: "$300",
value: "Where were the five world religions located around 1500 A.D. (C.E.)?"
}, {
name: "$400",
value: "What were the regional trading patterns about 1500 A.D. (C.E.)?"
}, {
name: "$500",
value: "Why were the regional trading patterns important?"
}],
[{
name: "$100",
value: "Who cares about the price of tea in China?"
}, {
name: "$200",
value: "Why did the chicken cross the road?"
}, {
name: "$300",
value: "How much wood could a woodchuck chuck if a woodchuck could chuck wood?"
}, {
name: "$400",
value: "How many SEO specialists does it take to change a light, bulb, lightbulb, energy, electricity?"
}, {
name: "$500",
value: "Where in the world is Carmen San Diego?"
}]
];
$(".rows").each(function (p) {
$("#row" + p).find("a").each(function (i) {
$(this).text(rows[p][i].name);
$(this).click(function () {
var value = rows[p][i].value;;
$("#clueContainer").html(value);
});
});
});
});
jsFiddle
I'm not familiar with jeopardy, but the list should contain the values from $100 to $500?
I modified your code, assuming the list is ascending: fiddle
No fiddle without code:
$(document).ready(function () {
var rowOne = {
"$100": "On the world political map, where were some of the major states and empires located about 1500 A.D. (C.E.)?",
"$200": "What were the artistic, literary, and intellectual ideas of the Renaissance?",
"$300": "Where were the five world religions located around 1500 A.D. (C.E.)?",
"$400": "What were the regional trading patterns about 1500 A.D. (C.E.)?",
"$500": "Why were the regional trading patterns important?"
};
$("li").on('click', 'a', function () {
var foo = $(this).text();
$('#clueContainer').text( rowOne[foo] );
});
});