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;
}
Related
Im trying to make a function that returns an Array (javascript). The original array contains objects (pizzas) and I have to return a new array WITHOUT the pizzas that contain pineapple on it. I dont seem to understand why it doesnt work.
I have tried to declare a new array and push() the [i] values that meet the criteria (!== 'pineapple'). But im clearly missing something.
I just started learning JS this week so tools like filter and map aren't possible for me yet.
thanks in advance!
const pizzas = [
{ type: 'margherita', size: '5' },
{ type: 'funghi', size: '6' },
{ type: 'hawaii', size: '7' },
{ type: 'vegetarian', size: '8' },
{ type: 'pineapple', size: '9' },
];
function filterPizzas(pizzas) {
const noPineapple = [];
for (let i = 0; i < pizzas.length; i++) {
if (pizzas[i].type !== 'pineapple') {
noPineapple.push(pizzas[i]);
}
}
return noPineapple;
}
Your code looks almost correct, although there is no use for storing the catalogue inside your FilterPizzas function and then also take in pizzas as a function argument. I assume you want to pass this list of pizzas (your catalogue) to your function and then return the filtered result.
const pizzas = [
{ type: 'margherita', price: '5' },
{ type: 'funghi', price: '6' },
{ type: 'hawaii', price: '7' },
{ type: 'vegetarian', price: '8' },
{ type: 'pineapple', price: '9' },
]
function filterPizzas(pizzas) {
const filteredPizzas = [];
for (let i = 0; i < pizzas.length; i++) {
if (pizzas[i].type !== 'pineapple') {
filteredPizzas.push(pizzas[i]);
}
}
return filteredPizzas
}
Have a look in the console of this working codesandbox example.
Option 1:
function filterPizzas(pizzas) {
const filteredPizzas = [];
for (let i = 0; i < pizzas.length; i++) {
const pizza = pizzas[i];
const pizzaType = pizza.type;
const isNotPineapple = pizzaType !== "pineapple";
if (isNotPineapple) {
filteredPizzas.push(pizza);
}
}
return filteredPizzas;
}
Option 2:
function filterPizzas(pizzas) {
let array = pizzas.filter(pizza => {
return pizza.type != 'pineapple';
});
return array;
}
//:(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.
So I have a problem with my var array to add a new chapter, how would I go about this would I have to do this:
array.push({
chapter: [
{
id: 2,
title: 'adsf',
content: '',
authorNotes: 'asdf'
}
]
});
RiTest.ts
import * as mongoose from 'mongoose';
const Scheme = mongoose.Schema;
export const RiTestScheme = new Scheme({
novelName: String,
novelAuthor: String,
novelCoverArt: String,
novelTags: Array,
chapters: [
{
id: Number,
title: String,
content: String,
authorNotes: String
}
]
});
export class RiTestController {
public addChapter(callback: (data) => void) {
var chapterInfoModel = mongoose.model('ChaptersTest', RiTestScheme);
var array = [
{
chapter: [
{
id: 0,
title: 'prolog',
content: 'conetntt is empty',
authorNotes: 'nothing is said by author'
},
{
id: 1,
title: 'making a sword',
content: 'mine craft end chapter',
authorNotes: 'nothing'
}
]
}
];
let newChapterInfo = new chapterInfoModel(array);
newChapterInfo.save((err, book) => {
if (err) {
return callback(err);
} else if (!err) {
return callback(book);
}
});
}
}
This doesn't work, var array doesn't get saved into let newChapterInfo = new chapterInfoModel(array); what I am trying to do add another chapter to array.chapter but the array doesn't get recognized in the chapterInfoModel() how would I fix this array and add an item to the array to create a new entry into this existing collection
thank for taking your time to answer my question.
You are trying to insert array of document to your collections, That the reason its not inserting into your collection.
Document.prototype.save() will insert only one document to your collection depends on your definition. So to insert chapter here is the code below,
//array as Object
var array = {
chapter: [
{
id: 0,
title: 'prolog',
content: 'conetntt is empty',
authorNotes: 'nothing is said by author'
},
{
id: 1,
title: 'making a sword',
content: 'mine craft end chapter',
authorNotes: 'nothing'
}
]
};
//Push to your chapter array
array.chapter.push({
id: 2,
title: 'adsf',
content: '',
authorNotes: 'asdf'
});
let newChapterInfo = new chapterInfoModel(array);
var productSchema = mongoose.Schema({
user_id:String,
products:[]
});
var Products = mongoose.model('Products', productSchema);
...
...
Products.find({},function(err,docs){
for(var i = 0; i < docs.length; i++){
var f = docs[i].products;
console.log(f);
});
Finally I can consoled this
{ _id: 8017ced8gf73kk25a8d9839x,
user_id: '739265b0dlskca14d8djd1a1',
__v: 0,
products:
[ { color: 'yellow', name: 'A' },
{ name: 'B', color: 'red' } ] }
But what I want is 'yellow' in Array!! not Array data.
I need to access the data in {}.
var f = docs[i].products.color;
And I tried this but it makes error.
If you want it in javascript you can run a loop through inner products array
Products.find({},function(err,docs){
for(var i = 0; i < docs.length; i++){
for(var j in docs[i].products){
if(docs[i].products[j] && docs[i].products[j].color){
console.log(docs[i].products[j].color)
}
}
});
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]);
}