//:(this is the assigment)Updating the number of items
In the addToCart function, update the element with ID itemCounter to the length of the cartItems array.
var cartItems = [];
var backpack = {
name: "Backpack",
price: 400
}
var camera = {
name: "Camera",
price: 300
}
function addToCart(item) {
cartItems.push(item);
}
I guess you need this
var cartItems = [];
var backpack = {
name: "Backpack",
price: 400
}
var camera = {
name: "Camera",
price: 300
}
function addToCart(item) {
cartItems.push(item);
document.getElementById("itemCounter").innerHTML = cartItems.length;
}
It is pretty simle question if you know basics of JS.
Related
I'm building a feed, where I want to unite two different structures and sort the feed by date, here's how I've tried. It shows mistakes in View. It writes either "compiler unable to type check in reasonable time", either something else that connects to the ForEach loop.
Maybe you have an idea what can be an issue? Or, if there's other way to build and sort the feed?
EDIT: The following error: "The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions"
class FeedViewModel: ObservableObject {
#Published var feed: [FeedCommonContent] = []
// download(ed) articles
self.feed.append(Article(id: doc.document.documentID, title: title, pic: pic, time: time.dateValue(), user: user))
// download(ed) tutorials
self.feed.append(Tutorial(id: doc.document.documentID, title: title, steps: [steps], notes: notes, pic: pic, time: time.dateValue(), user: user))
// sort the feed
self.feed.sort { (p1, p2) -> Bool in
return p1.time > p2.time
}
}
protocol FeedCommonContent {
// Define anything in common between objects
var time: Date { get set }
var id: String { get set }
var feedIdentity: FeedIdentity.RawValue { get } // Article, or Tutorial; or - { get set }
}
enum FeedIdentity: String {
// case Article, Tutorial
case Article = "Article"
case Tutorial = "Tutorial"
}
struct Article: Identifiable, FeedCommonContent {
var feedIdentity = FeedIdentity.Article.rawValue
var id: String = UUID().uuidString
var title: String
var pic: String
var time: Date
var user: User
}
struct Tutorial: Identifiable, FeedCommonContent {
var feedIdentity = FeedIdentity.Tutorial.rawValue
var id: String = UUID().uuidString
var titleImage: String
var name: String
var user: User
var inventory: [String]
var steps: [String]
var notes: String
var time: Date
var warnings: String
}
struct FeedView: View {
#StateObject var feedData = FeedViewModel()
var body: some View {
ScrollView {
ForEach(feedData.feed, id: \.self.id) { item in
// also tried type checking:
// if item is Article // or, if let article = item as? Article
if item.feedIdentity == FeedIdentity.Article.rawValue {
NavigationLink(destination: ArticleView(article: item, articleData: feedData)) {
ArticleUnitView(article: item, feedData: feedData)
}
} else if item.feedIdentity == FeedIdentity.Tutorial.rawValue { // if item is Tutorial
NavigationLink(destination: TutorialView(tutorial: item, feedData: feedData)) {
TutorialUnitView(tutorial: item, feedData: feedData)
}
}
}
}
When I did an array only of one of data structures, all worked. (i.e. either var articles: [Article] = [], or var tutorials: [Tutorial] = [] etc..)
this is the (test) code I used to show how to "sort" your feed by date, and display it in a View:
EDIT, using "Joakim Danielson" enum suggestion:
import SwiftUI
#main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
FeedView()
}
}
}
class FeedViewModel: ObservableObject {
#Published var feed: [FeedCommonContent] = []
// for testing
init() {
self.feed.append(Article(title: "article title", pic: "pic1", time: Date(), user: User()))
self.feed.append(Tutorial(titleImage: "title1", name: "tut1", user: User(), inventory: [], steps: [], notes: "note1", time: Date(), warnings: ""))
sortFeed()
}
func sortFeed() {
feed.sort { $0.time > $1.time }
}
}
protocol FeedCommonContent {
// Define anything in common between objects
var time: Date { get set }
var id: String { get set }
var feedIdentity: FeedIdentity { get } // Article, or Tutorial; or - { get set }
}
enum FeedIdentity: String {
// case Article, Tutorial
case Article
case Tutorial
}
struct User: Identifiable {
var id: String = UUID().uuidString
var name: String = "user"
}
struct Article: Identifiable, FeedCommonContent {
let feedIdentity = FeedIdentity.Article
var id: String = UUID().uuidString
var title: String
var pic: String
var time: Date
var user: User
}
struct Tutorial: Identifiable, FeedCommonContent {
let feedIdentity = FeedIdentity.Tutorial
var id: String = UUID().uuidString
var titleImage: String
var name: String
var user: User
var inventory: [String]
var steps: [String]
var notes: String
var time: Date
var warnings: String
}
struct FeedView: View {
#StateObject var feedData = FeedViewModel()
var body: some View {
ScrollView {
ForEach(feedData.feed, id: \.id) { item in
// switch item.feedIdentity {
// case FeedIdentity.Article:
// NavigationLink(destination: ArticleView(article: item, articleData: feedData)) {
// ArticleUnitView(article: item, feedData: feedData)
// }
// case FeedIdentity.Tutorial:
// NavigationLink(destination: TutorialView(tutorial: item, feedData: feedData)) {
// TutorialUnitView(tutorial: item, feedData: feedData)
// }
// }
// for testing
switch item.feedIdentity {
case FeedIdentity.Article:
NavigationLink(destination: Text(item.feedIdentity.rawValue + " " + item.id)) {
Text(item.feedIdentity.rawValue)
}
case FeedIdentity.Tutorial:
NavigationLink(destination: Text(item.feedIdentity.rawValue + " " + item.id)) {
Text(item.feedIdentity.rawValue)
}
}
}
}
}
Anyone can give me any suggestions ? I am trying to add an item in every 2 content. I couldn't see anything wrong with the code but why is the MyAds number repeating in all my ads entries ? it is supposed to start from MyAds0 and adding on.
MyAds2
Content1
Content2
MyAds2
Content3
Content4
MyAds2
Content5
Here is my code
const dummyData = [
{
name: 'Content1',
subtitle: 'Content1'
},
{
name: 'Content2',
subtitle: 'Content2'
},
{
name: 'Content3',
subtitle: 'Content3'
},
{
name: 'Content4',
subtitle: 'Content4'
},
{
name: 'Content5',
subtitle: 'Content5'
},
]
let TheData = InsertContent();
function InsertContent () {
let thisdata = [];
let adscounter = 0;
let tmpData = [ {name:'tmp', subtitle:'tmp'}];
for (let i=0; i < dummyData.length; i++){
if (Number.isInteger(i/2)) {
tmpData[0].name = 'MyAds' + adscounter;
tmpData[0].subtitle = 'My MyAds Sub' + adscounter;
thisdata = [...thisdata, tmpData[0]];
adscounter = adscounter + 1;
}
thisdata = [...thisdata, dummyData[i]];
}
return thisdata;
}
Actually the Problem is not with the logic but with the way you are using object and array with spread operator. You really don't have to use a object at first index in a array Instead you can directly use the object with spread operator to store into the array. I just modified your code to make it work as per your requirements.
const dummyData = [
{
name: 'Content1',
subtitle: 'Content1'
},
{
name: 'Content2',
subtitle: 'Content2'
},
{
name: 'Content3',
subtitle: 'Content3'
},
{
name: 'Content4',
subtitle: 'Content4'
},
{
name: 'Content5',
subtitle: 'Content5'
},
];
let TheData = InsertContent();
console.log(TheData);
function InsertContent () {
let thisdata = [];
let adscounter = 0;
let tmpData = {name:'', subtitle:''};
for (let i=0; i < dummyData.length; i++){
if (Number.isInteger(i/2)) {
tmpData = {
name: 'MyAds' + adscounter,
subtitle : 'My MyAds Sub' + adscounter
};
thisdata = [...thisdata, tmpData];
adscounter = adscounter + 1;
}
thisdata = [...thisdata, dummyData[i]];
}
return thisdata;
}
I got an array from database as
[
{id:
{unitno: 'abc'},
amount: 100},
{id:
{unitno: 'xyz'},
amount: 150}
]
Now my required answer is that should be in the following format,
[["abc",100],
["xyz",150]]
But after some coding I got an array of Array as shown below in the console
[0:[0:"abc",1:100]
1:[0:"xyz",1:150]]
Before question down / marking duplicate please read my requirement, and if its there then mark it and please post that link as per my required solution so i can get my solution from there
So any help will be great help....
You can do like this:
data = [
{id:
{unitno: 'abc'},
amount: 100},
{id:
{unitno: 'xyz'},
amount: 150}
]
var array =[]
data.forEach(function(item){
var tmpArray = []
tmpArray.push(item.id.unitno,item.amount)
array.push(tmpArray)
})
Now you will get your required data in the array.
I don't know how you got this below code, but that's invalid Array
[0:[0:"abc",1:100] 1:[0:"xyz",1:150]]
For your desired output you can do it with JavaScript, no need angular. Just run a simple for loop.
var temp1 = [{
id: {
unitno: 'abc'
},
amount: 100
}, {
id: {
unitno: 'xyz'
},
amount: 150
}];
var eee = [];
temp1.forEach(function(el) {
eee.push([el.id.unitno, el.amount])
});
console.log('eee:', eee);
Hope this is what you needed.
var arr = [{
id : { unitno: 'abc' },
amount: 100
},{
id : { unitno: 'xyz' },
amount: 150
}];
var result = [];
for (var i = 0; i < arr.length; i++) {
var newArray = [];
newArray.push( arr[i]["id"]["unitno"] );
newArray.push( arr[i]["amount"] );
result.push( newArray );
}
console.log( result );
Let's assume I have the following model in mongoose:
var Product = new Schema({
eanCode: String,
brandName: String,
productNameNl: String,
sex: String,
suggestedRetailPrice: Number
})
How can I write a function to query this model using an array with parameters? I want a generic function which can get anything from this model using an array of filter parameters. For example:
var filterArray = [
sex: "gents",
brand: "brandName"
];
var fieldsArray = ["sex", "brand", "productNameNl", "eanCode"];
var getBrandGentsProducts = getProducts(filterArray);
function getProducts(fields, filter){
Product.Find({fields}, {filter}).exec(function(err, products){
return products;
})
}
You can reduce your fieldArray to build key value pair for your filter
Example:
// create a filterMap for your fields and value that you want to filter with
var filterMap = {
sex: "gents",
brand: "brandName"
};
var fieldsArray = ["sex", "brand", "productNameNl", "eanCode"];
var getBrandGentsProducts = getProducts(filterArray);
function mapFilter(fields, filter) {
return fieldsArray.reduce(function (obj, field) {
if (filterMap[field]) {
obj[field] = filterMap[field];
}
return obj;
}, {});
}
function getProducts(fields, filter){
var filterPair = mapFilter(fields, filter);
//console.log(filterPair) //output { "brand": "brandName", "sex": "gents" }
Product.Find(filterPair).exec(function(err, products){
return products;
})
}
I've an array that contains assignments of employees on tasks, it looks like something like this:
$scope.assignments = [
{
employee: {
id:"1", firstname:"John", lastname:"Rambo"
},
task: {
name:"Kill everyone", project:"Destruction"
},
date: {
day:"01/01", year:"1985"
}
},
{
employee: {
id:"2", firstname:"Luke", lastname:"Skywalker"
},
task: {
name:"Find daddy", project:"Star Wars"
},
date: {
day:"65/45", year:"1000000"
}
},
{
employee: {
id:"1", firstname:"John", lastname:"Rambo"
},
task: {
name:"Save the world", project:"Destruction"
},
date: {
day:"02/01", year:"1985"
}
}
];
I would like to group by employee, for having something like this:
$scope.assignmentsByEmployee = [
{ //First item
id:"1",
firstname:"John",
lastname:"Rambo",
missions: [
{
name:"Kill everyone",
date:"01/01",
year:"1985"
},
{
name:"Save the world",
date:"02/01",
year:"1985"
}
]
},
{ //Second item
id="2",
firstname:"Luke",
lastname:"Skywalker",
missions: [
name:"Find daddy",
date:"65/45",
year:"1000000"
]
}
];
Is their a simple way to do this ? I tried something with a double forEach, but it leads me nowhere.
Hope I'm understandable :)
Thanks !
You should just be able to loop through the assignments array and create a 'keyed array' (which just means using an object in JavaScript) on employee ID. Then you just fill up the missions array as required.
Something like
// initialise a holding object
var assignmentsByEmployee = {};
// loop through all assignemnts
for(var i = 0; i < $scope.assignments.length; i++) {
// grab current assignment
var currentAssignment = $scope.assignments[i];
// grab current id
var currentId = currentAssignment.employee.id;
// check if we have seen this employee before
if(assignmentsByEmployee[currentId] === undefined) {
// we haven't, so add a new object to the array
assignmentsByEmployee[currentId] = {
id: currentId,
firstname: currentAssignment.employee.firstname,
lastname: currentAssignment.employee.lastname,
missions: []
};
}
// we know the employee exists at this point, so simply add the mission details
assignmentsByEmployee[currentId].missions.push({
name: currentAssignment.task.name,
date: currentAssignment.date.day,
year: currentAssignment.date.year
});
}
These leaves assignmentsByEmployee as an object, but you can simply foreach through it and convert it back to an array if required. E.g:
$scope.assignmentsByEmployee = [];
for(var employeeId in assignmentsByEmployee) {
$scope.assignmentsByEmployee.push(assignmentsByEmployee[employeeId]);
}