How can I improve adding/removing items to an array code - javascript

I have a list of items, I want to remove or add an item from myStockif it is selected or deselected. The problem I am having is once an item is selected the browser crushes. Is the a way I can do this better?
HTML:
<ion-list>
<div *ngFor="let item of stockList | speciesSearchPipe:listFilter.value">
<ion-item>
<ion-label>
{{ item.name_eng }}
<img src="./assets/images/species_icons/{{item.image_file}}" width="60" style="float: right;"/>
</ion-label>
<ion-checkbox class="item-avatar item-checkbox-right" color="dark" checked="false" (click)="selectSpecie(item)"></ion-checkbox>
</ion-item>
</div>
</ion-list>
TS:
let myStock = this.apiService.currentUser.data.coop.jdata;
if (myStock) {
for (let x = 0; myStock.stocklist.length > x; x++) {
myStock.stocklist["fish_species_id"] === item.fish_species_id ? myStock.stocklist.splice(x,1) : myStock.stocklist.push(item);
};
} else {
myStock = {};
myStock["stocklist"] = [];
myStock.stocklist.push(item);
};
console.log(myStock); // First log is as expected, then the app freezes

Try replacing your for-loop with this:
let index = myStock.stocklist.indexOf(item);
if(index >= 0) {
myStock.stocklist.splice(index, 1);
} else {
myStock.stocklist.push(item);
}
Full code:
let myStock = this.apiService.currentUser.data.coop.jdata;
if (myStock) {
let index = myStock.stocklist.indexOf(item);
if (index >= 0) {
myStock.stocklist.splice(index, 1);
} else {
myStock.stocklist.push(item);
}
} else {
myStock = {};
myStock["stocklist"] = [];
myStock.stocklist.push(item);
};
console.log(myStock);

if (!myStock) {
myStock = {
stockList: [item]
};
} else {
const index = myStock.stockList.findIndex(({item.fish_species_id}) => item.fish_species_id === item.fish_species_id);
if(index !== -1) {
myStock.stockList[index] = item;
} else {
myStock.stockList.push(item);
}
}
console.log(myStock);

Related

Angularjs ng-repeat passed index not defined

I am trying to toggle the button on and off in a ng-repeat, view on map works, but when it changes to remove marker, it pass me an error 'ReferenceError: passedIndex is not defined' in console log. Any way to fix that?
HTML:
<li class="displaySubCategory" ng-repeat="communityTheme in community | startFrom:currentPage*pageSize | limitTo:pageSize">
<div class="categoryImg">
<img src="img/csvIcon.png" />
<img src="img/shpIcon.png" />
</div>
<div class="categoryDesc">
<p>{{communityTheme.THEMENAME}}</p>
View on Map
Remove Marker
</div>
</li>
JS:
$scope.getMapData = function (msg, passedIndex) {
map.addLayer(cities);
$scope.Lng.length = 0;
$scope.Lat.length = 0;
$scope.dataLatLng.length = 0;
queryNameUrl = 'https://developers.onemap.sg/publicapi/themeapi/retrieveTheme?queryName=' + msg +
'&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjMsInVzZXJfaWQiOjMsImVtYWlsIjoicHVibGljQXBpUm9sZUBzbGEuZ292LnNnIiwiZm9yZXZlciI6ZmFsc2UsImlzcyI6Imh0dHA6XC9cL29tMi5kZmUub25lbWFwLnNnXC9hcGlcL3YyXC91c2VyXC9zZXNzaW9uIiwiaWF0IjoxNTQwOTI5OTE2LCJleHAiOjE1NDEzNjE5MTYsIm5iZiI6MTU0MDkyOTkxNiwianRpIjoiYjVkNmZkNGJhOWJiNGJiM2FkNWQzN2ZhNTAzMGIxYWEifQ.YQdfV43wrg8dX-He7-mwIL2Qhjsexq0tgNu5RotAdu4';
$http.get(queryNameUrl).then(function(response) {
$scope.apiResult = response.data.SrchResults;
$scope.apiResult.splice(0,1);
console.log($scope.apiResult)
for (var i= 0; i < $scope.apiResult.length; i++) {
if ($scope.apiResult[i].Type == "Point"){
$scope.apiResult[i].visibility = true;
console.log($scope.apiResult)
$scope.dataLatLng.push($scope.apiResult[i].LatLng)
$scope.Lat.push($scope.dataLatLng[i].split(',')[0]);
$scope.Lng.push($scope.dataLatLng[i].split(',')[1]);
L.marker([$scope.Lat[i], $scope.Lng[i]], {icon: greenIcon}).bindPopup($scope.apiResult[i].DESCRIPTION).addTo(cities);
}
// else if ($scope.apiResult[i].Type == "Polygon"){
// $scope.PolyLine.push($scope.apiResult[i].LatLng)
// console.log($scope.PolyLine)
// // for (var i = 0; i < $scope.PolyLine.length; i++) {
// // $scope.polyLineCord.push($scope.PolyLine[i])
// // // console.log($scope.polyLineCord)
// // }
// }
}
})
if($scope.community[passedIndex].visibility)
{
$scope.community[passedIndex].visibility = false;
}
else{
$scope.community[passedIndex].visibility = true;
}
}
Remove Marker:
$scope.removeMarker = function ($index) {
if($scope.community[passedIndex].visibility)
{
$scope.community[passedIndex].visibility =false;
cities.clearLayers();
}
else {
$scope.community[passedIndex].visibility = true;
}
}
Thanks for the help in advance !
You need to use track by $index
<li class="displaySubCategory" ng-repeat="communityTheme in community | startFrom:currentPage*pageSize | limitTo:pageSize track by $index">
and it should be passedIndex instead of $index in your removeMarker function
$scope.removeMarker = function (passedIndex) {

How to slice a part of string using typescript?

I am building up a custom select box with multi select as like angular material chips..
HTML
<div class="autocomplete">
<div class="chips-input-container">
<div class="col-md-4">
<div class="user-chip" *ngFor="let user of userSelects">
{{user.name}}
<span (click)="deleteSelects(user)" class="delete-icon-chip">✖</span>
</div>
</div>
<div class="col-md-4 form-label-group">
<input name="suggestion" type="text" id="autocomplete-input" class="form-control" placeholder="User" (click)="suggest()"
[(ngModel)]="userSelectsString" (keyup)="onKey($event)" id="autocomplete-input">
<label for="autocomplete-input" class="emailBox"></label>
<label class="fa fa-caret-down input-icon"></label>
</div>
</div>
<ul id="autocomplete-results" class="autocomplete-items" *ngIf="show">
<li *ngFor="let s of suggestions" [ngClass]="isSelected(s) ? 'selected-suggestion' : ''" (click)="selectSuggestion(s)">{{ s.name }}</li>
</ul>
</div>
TS:
import { Component } from '#angular/core';
import { FormControl } from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
suggestion: string = '';
typeahead: FormControl = new FormControl();
openSelectBox: boolean = false;
fieldHistory: string[] = [];
inputValue: string;
autocomplete_results: any;
input = document.querySelector('#autocomplete-input');
userSelectsString = '';
name = 'Angular';
userSelects = [];
suggestions = [{"id":"001","name":"mango"},{"id":"002","name":"apple"},{"id":"003","name":"banana"},{"id":"004","name":"pine"},{"id":"005","name":"orange"},{"id":"006","name":"chery"},{"id":"007","name":"watermelon"},{"id":"008","name":"grapes"},{"id":"009","name":"lemon"}];
show: boolean = false;
suggest() {
this.show = true;
}
isSelected(s:any) {
return this.userSelects.findIndex((item) => item.id === s.id) > -1 ? true : false;
}
selectSuggestion(s) {
this.userSelects.find((item) => item.id === s.id) ?
this.userSelects = this.userSelects.filter((item) => item.id !== s.id) :
this.userSelects.push(s);
this.show = false;
}
deleteSelects(s) {
this.userSelects = this.userSelects.filter((item) => item.id !== s.id);
}
assignToNgModel() {
this.userSelectsString = '';
this.userSelects.map((item) => this.userSelectsString += item.name + ' ');
}
onKey(e) {
this.inputValue = e.target.value;
if (this.inputValue.length > 0) {
var people_to_show = [];
this.autocomplete_results = document.getElementById("autocomplete-results");
this.autocomplete_results.innerHTML = '';
people_to_show = this.autocomplete(this.inputValue);
for (let i = 0; i < people_to_show.length; i++) {
this.autocomplete_results.innerHTML += '<li>' + people_to_show[i] + '</li>';
}
this.autocomplete_results.style.display = 'block';
} else {
people_to_show = [];
this.autocomplete_results.innerHTML = '';
}
}
autocomplete(val) {
var people_return = [];
for (let i = 0; i < this.suggestions.length; i++) {
if (val === this.suggestions[i].slice(0, val.length)) {
people_return.push(this.suggestions[i]);
}
}
return people_return;
}
}
As of selection and deletion part, everything works fine but when i implemented autocomplete, i am unable to get result as i am using slice for the array of objects.
My data is:
suggestions = [{"id":"001","name":"mango"},{"id":"002","name":"apple"},{"id":"003","name":"banana"},{"id":"004","name":"pine"},{"id":"005","name":"orange"},{"id":"006","name":"chery"},{"id":"007","name":"watermelon"},{"id":"008","name":"grapes"},{"id":"009","name":"lemon"}];
In the for loop, i am getting error as Property 'slice' does not exist on type '{ "id": string; "name": string; }'. in the linethis.suggestions[i].slice(0, val.length),
for (let i = 0; i < this.suggestions.length; i++) {
if (val === this.suggestions[i].slice(0, val.length)) {
people_return.push(this.suggestions[i]);
}
}
If i give any inside suggestions: any = [{"id":"001","name":"mango"},...}], it is showing slice is not a function.
Kindly help me to achieve the result of autocomplete.
Stackblitz: https://stackblitz.com/edit/angular-euuvxw
You probably want to slice the name, not the entire suggestion object. And looking at how you are using the result, you probably want to push only the name into people_return too:
for (let i = 0; i < this.suggestions.length; i++) {
if (val === this.suggestions[i].name.slice(0, val.length)) {
// ^^^^
people_return.push(this.suggestions[i].name);
}
}
You need to use slice() in array type value. In your case it is this.suggestions so use this.suggestions.slice(0, val.length)

Unable to add the item in array on scan in Angular 2

I am developing an application using Angular 2.. In my application I am using barcode scanner to scan in the text field and storing those items in the array.
When I scan the item get added to array, but when I scan another item the old item it replace the old value in array.
Below is the piece of code which I am using. Please help me if you see any fix for the weird issue.
import { Component,ViewChild,Input, Output,OnInit,ChangeDetectorRef } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HeaderComponent } from '../common/header.component';
//import { SaleCart } from '../model/SaleCart';
//import * as $ from "jquery";
declare var jQuery: any
#Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./posapp.component.css']
})
export class TestComponent implements OnInit{
title = 'Treewalker POS';
public cartItems = [];
public query;
public filteredList = [];
public products = [{"id":"3","name":"Pears Soap Original 75gm","sku":"89675432189","price":"32.00","special_price":"32.00","qty":null,"barcode":"89675432189","tax":"5","discount":"0"},{"id":"1","name":"Rin","sku":"1111111111111","price":"11.00","special_price":"11.00","qty":"10.000","barcode":"1111111111111","tax":"5","discount":"0"},{"id":"2","name":"Test 1","sku":"23456","price":"10.00","special_price":"10.00","qty":"10.000","barcode":"23456","tax":"5","discount":"0"}];
constructor() {
}
ngOnInit() {
}
add(item) {
/* check the items in the json data */
let flag = false;
var foodItem = {};
for (let product of this.products) {
if(product.barcode == item) {
flag = true;
foodItem['ctr'] = 1;
foodItem['item'] = product;
break;
}
}
let localCart = [];
if(sessionStorage.getItem("cart")){
localCart = JSON.parse(sessionStorage.getItem("cart"));
//console.log(JSON.stringify(localCart));
}
//console.log("food "+JSON.stringify(this.cart));
if(flag && localCart.length) {
let exist = 0;
for(let i=0; i < localCart.length; i++) {
if(localCart[i].item.barcode == item) {
localCart[i].ctr = parseInt(localCart[i].ctr) + 1;
//console.log("#### "+this.cart[i].ctr+" --- "+item);
exist = 1;
}
}
if(!exist){
localCart.push(foodItem);
}
sessionStorage.setItem("cart",JSON.stringify(localCart));
//this.barcode = "";
}else if(flag){
localCart.push(foodItem);
sessionStorage.setItem("cart",JSON.stringify(localCart));
}
//this.cart = JSON.parse(sessionStorage.getItem("cart"));
//this.itemsCnt = localCart.length;
//console.log("--- "+this.itemsCnt);
console.log(JSON.parse(sessionStorage.getItem('cart')));
//this.onScanProduct.emit(localCart);
}
filter(e) {
//e.preventDefault();
if (this.query !== ""){
this.filteredList = this.products.filter(function(el){
if(el.barcode.toLowerCase() == this.query.toLowerCase()) {
return el.barcode.toLowerCase() == this.query.toLowerCase();
}else{
return el.barcode.toLowerCase().indexOf(this.query.toLowerCase()) > -1;
}
}.bind(this));
/* scanned item will be added to the cart */
console.log(this.filteredList.length);
if(this.filteredList.length > 0 && e.which == 13){
//console.log(JSON.stringify(this.filteredList));
for (let product of this.filteredList) {
//console.log(filter.barcode+"=="+this.query);
if(product.barcode == this.query) {
this.add(product.barcode);
jQuery('#barcode').val("");jQuery('#barcode').focus();
this.filteredList = [];
}
}
}
}else{
this.filteredList = [];
}
}
}
Below is the html template
<div class="content-wrapper">
<section class="content">
<form>
<div class="row">
<!-- sales item add window -->
<!-- end -->
<div class="col-sm-4">
<div class="box box-primary">
<div class="box-body">
<div class="form-group">
<div class="row">
<div class="col-md-9">
<!--<input type="text" class="form-control" id="barcode" name="barcode" [(ngModel)]="barcode" (ngModelChange)="add($event)"
placeholder="Enter item code or scan the barcode" autocomplete="off" />-->
<input id="barcode" type="text" class="form-control validate filter-input" name="query" [(ngModel)]="query" (keyup)="filter($event)" placeholder="Enter item code or scan the barcode" autocomplete="off" [ngModelOptions]="{standalone: true}">
</div>
<div class="suggestions" *ngIf="filteredList.length > 0">
<ul>
<li *ngFor="let item of filteredList" >
<a (click)="select(item)" href="javascript:;">{{item.barcode}} {{item.name}}</a>
</li>
</ul>
</div>
<div class="col-md-3">
<button type="button" class="btn btn-primary" (click)="createnewproduct(newproduct)">New Product</button>
</div>
</div>
</div>
</div> <!-- end of box body -->
</div>
</div>
</div><!-- end of row -->
</form>
</section>
</div>
Below is the input field which is being used to scan the barcode
<input id="barcode" type="text" class="form-control validate filter-input" [(ngModel)]="query" (keyup)="filter()" placeholder="Enter item code or scan the barcode" autocomplete="off">
I am assuming you are using only the function add. I tried to implement in a javascript like in the following code but I am pretty sure you are referencing that object somewhere else and you are changing it. That's my conclusion but I might be wrong.
var factoryP = (function(){
function P() {
this.cart = [];
this.products = [{'barcode': 1, 'name': 'a'}, {'barcode': 1, 'name': 'b'}]
}
function add(item) {
/* check the items in the json data */
//console.log("cart length "+JSON.stringify(this.cart));
let flag = false;
var foodItem = {};
for (let product of this.products) {
if(product.barcode == item) {
//console.log("check "+item);
flag = true;
foodItem['ctr'] = 1;
foodItem['item'] = product;
break;
}
}
if(flag && this.cart.length) {
let exist = 0;
for(let i=0; i < this.cart.length; i++) {
if(this.cart[i].item.barcode == item) {
//console.log("Same product");
this.cart[i].ctr = parseInt(this.cart[i].ctr) + 1;
exist = 1;
}
}
if(!exist){
console.log(foodItem);
this.cart.push(foodItem);
}
}else if(flag){
console.log("step 4 "+item);
this.cart.push(foodItem);
}
}
P.prototype.add = add;
return new P();
});
instanceP = factoryP();
instanceP.add(1);
instanceP.add(1);
instanceP.add(1);
instanceP.add(2);
console.log(instanceP.cart[0].ctr)
//output 3
instanceP.cart[1].ctr
//output 1
Check your code here. Every time you are initializing the foodItem array with empty array. So whenever code will call add method, it will first empty your foodItem array.
Please check my comment in your code below:
add(item) {
let flag = false;
//Akshay: You need to make your changes here. Initialize your foodItem array out of this scope
var foodItem = {};
for (let product of this.products) {
if(product.barcode == item) {
//console.log("check "+item);
flag = true;
foodItem['ctr'] = 1;
foodItem['item'] = product;
break;
}
}

Angular filtering array of object if certain property is false?

so i have an array of object i am ng-repeating and works beautifully, but i want to list the array of objects that have a property value of 'true' . i feel like the built in angualr filter should be sufficient. But cant get it to work
here is my attempt . Basically i only want asset.name , asset.status etc of the objects that have disabled property 'true'
<md-virtual-repeat-container id="vertical-container" ng-show="$ctrl.infiniteAssets.getLength() > 0 && $ctrl.switch">
<md-list>
<md-list-item class="list-page" md-on-demand md-virtual-repeat="asset in $ctrl.infiniteAssets | assetsFilter:$ctrl.searchValue | filter:{disabled:true}:true" ng-click="$ctrl.loadDetail(asset)">
<span class="search-status" style="border-left-color:{{asset.statusColor}};"></span>
<p >{{asset.name}} </p>
<label hide-xs ng-if="asset.disabled" class="ng-animate-disabled">
<md-chips>
<md-chip >{{'LABELS.DISABLED' | translate}}</md-chip>
</md-chips>
</label>
<label ><i>{{asset.status || 'UNKNOWN'}}</i></label>
<md-button aria-label="Delete Asset" class="md-icon-button md-warn" layout-padding ng-click="$ctrl.deleteAsset(asset)">
<md-icon md-svg-icon="delete" class="modelTrashIcon"></md-icon>
</md-button>
<md-divider></md-divider>
</md-list-item>
</md-list>
</md-virtual-repeat-container>
$onInit = () => {
this.swtich = false;
this.hideToolbarTools = false;
this.searchOpen = false;
this.componentList = [];
this.alertCount = 0;
this.loading = false;
this.disableTitle = false;
this.searchValue = "";
this.first = true;
this.settings = {
printLayout: true,
showRuler: true,
showSpellingSuggestions: true,
presentationMode: 'edit'
};
this.global = this.$rootScope;
this.$rootScope.$on('transform-toolbar-open', () => {
//hide toolbar controls on mobile
if(this.$mdMedia('xs')){
this.hideToolbarTools = true;
}else{
this.hideToolbarTools = false
}
})
this.$rootScope.$on('transform-toolbar-close', () => {
//show toolbar controls
this.hideToolbarTools = false;
})
this.loadAssets()
}
loadAssets = () => {
var self = this;
self.infiniteAssets = {
numLoaded_: 0,
toLoad_: 0,
items: [],
pageNum:1,
virtualIndex:0,
getItemAtIndex: function (index) {
this.virtualIndex=index;
if (index > this.numLoaded_) {
this.fetchMoreItems_(index);
return null;
}
return this.items[index];
},
// Required.
getLength: function () {
if (this.virtualIndex > this.numLoaded_) {
return this.numLoaded_ ;
}else{
return this.numLoaded_ + 5 ;
}
},
fetchMoreItems_ : function (index) {
if (this.toLoad_ < index) {
self.loading = true;
this.toLoad_ += 20;
self.siAsset.getAssets(this.pageNum++,20)
.then(angular.bind(this, function (assets) {
//this.objLength = assets.length;
if(! assets.statusCode){
this.items = this.items.concat(assets);
this.toLoad_ = this.items.length;
this.numLoaded_ = this.toLoad_;
}
self.loading = false;
}))
}
}
};
console.log('check',this.infiniteAssets)
}
Actually the filter:{disabled:true} will work fine.
If it is not work I think you can filter them in you script side as
var infiniteAssets = infiniteAssets.filter(i=>i.disabled == true);
or use angular filter
var infiniteAssets = $filter('filter')(infiniteAssets,{disabledled:true})
you can try by putting ng-if condition below the ng-repeat
<md-virtual-repeat-container id="vertical-container" ng-show="$ctrl.infiniteAssets.getLength() > 0 && $ctrl.switch">
<md-list>
<md-list-item class="list-page" md-on-demand md-virtual-repeat="asset in $ctrl.infiniteAssets ng-click="$ctrl.loadDetail(asset)">
<div ng-if="asset.disabled">
<span class="search-status" style="border-left-color:{{asset.statusColor}};"></span>
<p >{{asset.name}} </p>
<label hide-xs ng-if="asset.disabled" class="ng-animate-disabled">
<md-chips>
<md-chip >{{'LABELS.DISABLED' | translate}}</md-chip>
</md-chips>
</label>
<label ><i>{{asset.status || 'UNKNOWN'}}</i></label>
<md-button aria-label="Delete Asset" class="md-icon-button md-warn" layout-padding ng-click="$ctrl.deleteAsset(asset)">
<md-icon md-svg-icon="delete" class="modelTrashIcon"></md-icon>
</md-button>
<md-divider></md-divider>
</div>
</md-list-item>
</md-list>
</md-virtual-repeat-container>
i decide to create a whole new function for disabled ones and use javascript filter to achieve this feature
if(! asset.statusCode){
let disabled = asset.filter((a)=>{
return a.disabled ==true
})
this.items = this.items.concat(disabled);
this.toLoad_ = this.items.length;
this.numLoaded_ = this.toLoad_;
}

Difficulty with error "Uncaught TypeError: Cannot read property 'name' of undefined"

I've been working on a JavaScript code in order to make a checkout cart of a pizza, but have been having an issue with the showCart function.
let pizzas=[
{ name:"Pepperoni", img:"pizza.png", price:8.99},
{ name:"Alfredo", img:"pizza.png", price:9.99},
{ name:"Cheese", img:"cheese.png", price:7.99}
];
function registerButtonEvents()
{
let buttons=document.getElementsByTagName("button");
for(let i = 0; i < buttons.length-1; i++)
{
buttons[i].addEventListener("click", function() {
addToCart(i);
});
}
let number = localStorage.getItem("number");
if(number == null)
number = 0;
document.getElementById("num").innerHTML = number;
}
function addToCart(pId)
{
let cartJ = localStorage.getItem("cart");
let cart;
if(cartJ===null) //Cart is empty
{
cart=[];
}
else
{
cart=cartJ.split(",");
}
cart.push(pId);
let number= localStorage.getItem("number");
if(number===null)
number = 0;
document.getElementById("num").innerHTML = `${++number}`;
localStorage.setItem("cart", cart.toString());
localStorage.setItem("number", number);
}
function clearCart()
{
localStorage.removeItem("cart");
localStorage.removeItem("num");
}
function showCart()
{
let cartJ = localStorage.getItem("cart");
let cart = [];
let info = "";
if(cartJ === null)
{
document.getElementById("myCart").innerHTML=`<h2>No items in cart!</h2>`;
}
else
{
cart = cartJ.split(",");
for (let i in cart)
{
let item = pizzas[cart[i]];
info+=
`<div class="row">
<div class="col-md-2 text-center">
<h3>${item.name}</h3>
</div>
<div class="col-md-2 text-center">
<img class="pizza" src="./images/${item.img}" alt="pepperoni">
</div>
<div class="col-md-2 text-center">
<h3>${item.price}</h3>
</div>
<div class="col-md-2 text-center">
<button type="button" class="btn btn-primary" onclick="removePizza(${i})">Remove</button>
</div>
</div>
`;
}
document.getElementById("myCart").innerHTML=info;
}
}
function removePizza(piz)
{
var cart = localStorage.getItem("cart");
cart = cart.split(",");
cart.splice(piz, 1);
if (cart.length == 0)
clearCart();
else
{
localStorage.setItem("cart", cart);
localStorage.setItem("number",cart.length);
}
showCart();
}
Developer tools tell me that the error is in the line in:
let item = pizzas[cart[i]];
but I don't necessarily understand why. If anyone could send some feedback it would be greatly appreciated.
The problem is when you access <h3>${item.name}</h3>. Your item is undefined there because your cart (cart = cartJ.split(",");) probably stores some strings like "Pepperoni" (as you split them using a comma) and after that you want to access the pizzas array using one of those strings instead of an index.

Categories