Search array for string - returning -1 - javascript

I've been reading lots of StackOverflow answers which tell me that, in Javascript, the best way to search an array for a particular string is use indexOf(). I have been trying to make this work for a while now, and I need some help with it.
I am making a shop in a text-adventure game. These are the values I am using:
The array shopCosts:
shopCosts = [20, 25];
The array shopItems:
shopItems = [["Sword", "Shield"]];
I dynamically create radiobuttons by looping through shopItems:
for(var i = 0; i < array.length; i++)
{
// Create the list item:
var item = document.createElement('li');
// Set its contents:
item.appendChild(document.createTextNode(array[i] + " - " + shopCosts[i] + " Gold"));
// Add it to the list:
list.appendChild(item);
var label = document.createElement("label");
var radio = document.createElement("input");
var text = document.createTextNode(array[i]);
radio.type = "radio";
radio.name = "shop";
radio.value = array[i];
radio.onclick = function () { addValue(this.getAttribute("value"), shopCosts, shopItems) }
label.appendChild(radio);
label.appendChild(text);
document.body.appendChild(label);
}
This is the part in question:
radio.onclick = function () { addValue(this.getAttribute("value"), shopCosts, shopItems) }
My logic was basically to assign values to each dynamically created radiobutton, and if one was pressed, get the value (so, the name of the item you wanted to buy) and then search shopItems for that particular string for the index value. Once I had that, I would look in the same "parallel" list shopCosts to find the price.
I used console.log() to see what variables were in play. When I clicked on the radio button, this function is called:
function addValue(nameOfItem, shopCosts, shopItems)
{
var positionOfShopItem = shopItems.indexOf(nameOfItem);
console.log(positionOfShopItem);
console..log(nameOfItem);
console.log(shopItems);
}
Surely, the console.log() would return the position of the named item? To prove to myself I'm not going crazy, here's what the Dev Tools say:
-1
Sword
[Array[2]]
0: "Sword"
1: "Shield"
Sword is clearly in the array, in position 0, so why is indexOf() returning -1?
Any help appreciated!

As I alluded to in my comment, its because shopItems does not contain an array of strings, it contains a single element, where that one element is an array of strings. I suspect your code would work just fine if you removed the extra square braces
var shopItems = ["Sword", "Shield"];

I realize you've already fixed the bug, but I urge you to consider a different approach to the problem. These two principles will not only solve the problem in a cleaner way, but they also give you a new way to think about similar problems in the future:
Never use parallel arrays. Use a single array of objects instead.
In your main loop that appends the items, put the main body of the loop in a function.
If you follow these two ideas you gain several benefits. The code becomes much more straightforward, easier to maintain, and you don't have to do any array lookups at all!
Each shop item is packaged up as a single object in the array, like this:
var shopItems = [
{ name: 'Sword', cost: 20 },
{ name: 'Shield', cost: 25 }
];
So if you have a reference to the shop item as a whole, say in a variable called shopItem, then you automatically have all of its properties available: shopItem.name and shopItem.cost. This lets you also easily add more bits of data to a shop item, e.g.
var shopItems = [
{ name: 'Sword', cost: 20, dangerous: true },
{ name: 'Shield', cost: 25, dangerous: false }
];
and now shopItem.dangerous will give you the appropriate value. All without any array lookups.
Making the main loop body into a function adds a further benefit: Inside that function, its parameters and local variables are preserved each time you call the function (this is called a closure). So now you don't even have to fetch the list item value and look it up - you already have the appropriate shopItem available in the code.
Putting this together, the code might look like this:
var shopItems = [
{ name: 'Sword', cost: 20, dangerous: true },
{ name: 'Shield', cost: 25, dangerous: false }
];
var list = document.getElementById( 'list' );
for( var i = 0; i < shopItems.length; ++i ) {
appendShopItem( shopItems[i] );
}
// Alternatively, you could use .forEach() instead of the for loop.
// This will work in all browsers except very old versions of IE:
// shopItems.forEach( appendShopItem );
function appendShopItem( shopItem ) {
// Create the list item:
var item = document.createElement( 'li' );
// Set its contents:
item.appendChild( document.createTextNode(
shopItem.name + ' - ' + shopItem.cost + ' Gold'
) );
// Add it to the list:
list.appendChild( item );
var label = document.createElement( 'label' );
var radio = document.createElement( 'input' );
var text = document.createTextNode( shopItem.name );
radio.type = 'radio';
radio.name = 'shop';
radio.value = shopItem.name;
radio.onclick = function () {
addValue( shopItem );
};
label.appendChild( radio );
label.appendChild( text );
document.body.appendChild( label );
}
function addValue( shopItem ) {
console.log( shopItem );
alert(
shopItem.name +
' costs ' + shopItem.cost + ' and is ' +
( shopItem.dangerous ? 'dangerous' : 'not dangerous' )
);
}
New fiddle (with a tip of the hat to Jamiec for the original fiddle)
As you can see, this makes the code much easier to understand. If you have a shopItem, you automatically have its name, cost, and any other property you want to add. And most importantly, you never have to keep track of putting your values in the same order in two, three, or even more different arrays.

shopItems is an Array of Arrays. The 0 index of shopItems contains another array which contains:
["Sword", "Shield"]
So when you are trying to find the "Sword" item or "Shield" Item inside of shopItems it is returning -1 because it cannot find either inside of the array.
Change
shopItems = [["Sword", "Shield"]];
To
shopItems = ["Sword", "Shield"];
And that will fix your issue.

I've fixed it!
Removing the double square brackets resulted in this mess. So, as a workaround, I simply added [0] to var positionOfShopItem = shopItems.indexOf(nameOfItem); to get var positionOfShopItem = shopItems[0].indexOf(nameOfItem);
Thanks for everyone's help.

Related

How to access object with a randomly chosen name stored in a variable?

I've got 16 objects with names like: aBoard, bBoard, cBoard and so on,
eg. let aBoard = { currentValue: 0, valuesHistory: [], ID: "unitA", borderValues: [1, 0, 0, 1], free: true };
I have an array of corresponding names, randomly chose one of them and change it so it matches the name of one of the objects.
const BOARDARRAY = ["unitA", "unitB", "unitC", "unitD", "unitE", "unitF", "unitG", "unitH", "unitI", "unitJ", "unitK", "unitL", "unitM", "unitN", "unitO", "unitP"];
let randomizer = Math.floor(Math.random()*16);
currentBoardTile = BOARDARRAY[randomizer];
let temp = (currentBoardTile.charAt(currentBoardTile.length -1).toLowerCase());
JSObjectBoardUnit = (temp + "Board");
How to access the object using my JSObjectBoardUnit?
In other words, how to make JS "understand" that I want to treat JSObjectBoardUnit value (string) as a value of the object address?
Eg. Let's day JSObjectBoardUnit = aBoard;
Basically the outcome I want is: aBoard.key1 = JSObjectBoardUnit.key1.
I'd love to use the value stored in JSObjectBoardUnit to access the name of the predefined object aBoard.
I'm not sure to understand well your question but I think this 2 methode could maybe help you.
You can access attribute of a object with a string by using
const obj = {toto: 1};
const name = "toto";
console.log(obj["toto"]); // 1
console.log(obj[name]); // here we use variable and the result is 1
so you could store all yoyr object inside one and do this.
const allBoard = {
"aboard": null, // do not put null use your board
}
console.log(allBoard[(temp + "board")]); // display the temp + board attribute so if temps is equal to a then it will get the aboard
this is what you want, getting object from a string.
But I saw that the aboard also have an id attribute with "unitA"
Instead you could build an array of aboard, bboard ....
and use the Array.find() methode that will return the object that match the condition.
in your case
const myBoardArray = [{ currentValue: 0, valuesHistory: [], ID: "unitA", borderValues: [1, 0, 0, 1], free: true }, ....];
let randomizer = Math.floor(Math.random()*16);
currentBoardTile = BOARDARRAY[randomizer];
myBoardArray.find((board) => board.ID === currentBoardTile);
2 options
Put the boards in a list, and iterate over them with a for loop. In the for loop, use an if statement to see which Id matches the board you want.
let boards = [aBoard , bBoard, cBoard];
boards.forEach(board=> {
if (board.ID == currentBoardTile) {
//do something
}
});
Create a dictionary where the key is the board id and the respective object is the value. Use the board id to get the respective value.
var boards = {
"unitA" : boardA,
"unitB" : boardB,
....
};
currentBoardTile = BOARDARRAY[randomizer];
console.log(currentBoardTile + " : " + boards[currentBoardTile]);

I'm making a level maker with a preview from the code generated by the level maker, how could I do this?

I have made a Level Generator. Basically there is a 3 by 20 grid of squares, and you can select either one and depending on what you select when you click the button to generate it generate some code for you into a variable (string). It works perfectly but how am I going about to then get that generated code and turn it into a preview.
So far I found out using the keyword eval() but this only does the last line? Any ideas?
Here is a picture of what the layout is:
The Website So Far
The code that I originally had to detect the code was:
if (container.childNodes[index].innerText == 'pos3') {
if (container.childNodes[index].id == '1 second') {
text = text + '\n' + 'cube1 = new theCubeCreator(pos3, 0, 2, 1000),'
//amtselected = amtselected + 1
}....
Something like that then I would bundle it all up with this
var pos1 = 125 //middle
var pos2 = 70 //left
var pos3 = 180 //right
text = text + '\n' + 'cube1 = new theCubeCreator(pos2, 0, 2, 1000)' // Must add this to make it a end
var evaluation = eval(text)
console.log(evaluation);
Sorry if this is hard to read or if you want me to send examples.
What you are doing is bad practice. You should make an object that holds the functions and a generator function that converts and object into a function.
// object for the function / class you want to run
var data = {
name: "console.log",
isClass: false,
params: ["pos2", 0, 2, 1000],
};
var domParse = {
name: "DOMParser",
isClass: true,
params: ["<div>Hello World</div>", "text/html"],
};
var funcs = {
DOMParser: (args) => {
const dom = new DOMParser();
return dom.parseFromString(...args);
},
"console.log": (args) => console.log(...args),
};
// function to generate a function from the object.
function generate({ name, isClass, params }) {
return funcs[name](params);
}
generate(data); // console.log's pos2 0 2 1000
generate(domParse); // creates a DOM object
I took another way than doing eval() (well i still used eval). What I was doing was, to have a variable let text = '' then adding onto that variable doing something like this text = text + \n + '...'
Already this is bad so i took a different approach. all i changed was instead of having a string variable i would have a Array to store my code. Declearing it like this let text = [] then using push() to add the code to it, like so text.push(eval(...)).
Thats what i did to complete to fix my problem if you have any other way or eisier to follow (and yes i know this is messy) then comment (:

Mix clickable row and unclickable row on slickgrid

For my columns definition.
var columns = [
{id: "label", name: "point", formatter:this.clickableFormatter,field: "point",width: 150},
then I add clickhander for it.
chart.addClickHandler(){
}
Also I use clickableFormatter for this.
clickableFormatter(row,cell,value,columnDef,dataContext){
return "<span style='cursor:pointer;'>" + value + "</span>";
}
From these code. my table rows are clickable and I can show the user where is clickable by changing pointer.
However now I want to make one row unclickable.
(for example total row)
Is it possible to prevent click event for one low??
And is it possible to use another formatter for one row?
I gave the data from for loop and add total seperately.
for (var k = 0 ; k < data.length ;k++){
var temp = new Array();
temp['id'] = data[k]['id'];
temp['point'] = data[k]['point'];
ret.push(temp);
}
ret.push({
'id' : "total",
"point" : pointTotal,
});
In your formatter, you have access to the value of the cell, so if value==='total', just return an empty string.
Also FYI, I don't think you need the for loop in your code (you could just leave it out entirely), unless you're using it to calculate the total, but you don't seem to be doing that.
If you think that you need it for creating the array objects, you're misunderstanding arrays in javascript, what you're actually setting is object properties, and it would be usual to initialise with var temp = { }; rather than as Array.
It may not make sense at first, but everything in javascript is an object, including arrays and functions. So you can add object properties to anything.
somevar[numericVal] = x; // set array element, somevar must be type Array
somevar['stringVal'] = x; // set object property 'stringVal'
somevar.stringVal = x; // identical to above line, different way of specifying

How to find the position of all array items from a loop

I'm brand new to programming so I apologize if this is a simple question.
I had a unique practice problem that I'm not quite sure how to solve:
I'm dealing with two arrays, both arrays are pulled from HTML elements on the page, one array is representing a bunch of states, and the next array is representing their populations. The point of the problem is to print the name of the states and their less than average populations.
To find and print all of the populations that are less than the average I used this code:
function code6() {
// clears screen.
clr();
// both variables pull data from HTML elements with functions.
var pop = getData2();
var states = getData();
var sum = 0;
for( var i = 0; i < pop.length; i++ ){
sum += parseInt( pop[i], 10 );
var avg = sum/pop.length;
if (pop[i] < avg) {
println(pop[i]);
// other functions used in the code to get data, print, and clear the screen.
function getData() {
var dataSource = getElement("states");
var numberArray = dataSource.value.split('\n');
// Nothing to split returns ['']
if (numberArray[0].length > 0) {
return(numberArray);
} else {
return [];
}
}
// Get the data from second data column
function getData2() {
var dataSource = getElement("pops");
var numberArray = dataSource.value.split('\n');
// Nothing to split returns ['']
if (numberArray[0].length > 0) {
return(numberArray);
} else {
return [];
}
}
// Clear the 'output' text area
function clr() {
var out = getElement("output");
out.value = "";
}
// Print to the 'output' HTML element and ADDS the line break
function println(x) {
if (arguments.length === 0) x = '';
print(x + '\n');
}
Now I just need to know how to get the value of these positions within the array so I can pull out the same positions from my states array and display them both side by side. Both arrays have the identical amount of items.
I hope this makes sense and thanks in advance to anyone who has time to take a look at this.
Best regards,
-E
Its a little hard to tell what you are trying to accomplish, but I guess you are going for something like:
'use strict'
function code6() {
const populations = ['39000000', '28000000', '21000000'];
const stateNames = ['california', 'texas', 'florida'];
const states = populations.map((population, i) => ({
'name': stateNames[i],
'population': Number(population),
}));
const sum = states.reduce((sum, state) => sum + state.population, 0);
const average = sum / populations.length;
states
.filter(state => state.population < average)
.forEach(state => {
const name = state.name;
const population = state.population;
console.log(`state name: ${name}, population: ${population}`);
});
}
// run the code
code6();
// state name: texas, population: 28000000
// state name: florida, population: 21000000
I took the liberty of refactoring your code to be a little more modern (es6) and Idiomatic. I hope its not to confusing for you. Feel free to ask any questions about it.
In short you should use:
'use strict' at the top of your files
const/let
use map/filter/forEach/reduce to iterate lists.
use meaningfull names
, and you should avoid:
classic indexed for-loop
parseInt
, and pretty much never ever use:
var
If your states array is built with corresponding indices to your pop one, like this:
states; //=> ['Alabama', 'Alaska', 'Arizona', ...]
pop; //=> [4863300, 741894, 6931071, ...]
then you could simply update your print statement to take that into account:
if (pop[i] < avg) {
println(state[i] + ': ' + pop[i]);
}
Or some such.
However, working with shared indices can be a very fragile way to use data. Could you rethink your getData and getData2 functions and combine them into one that returns a structure more like this the following?
states; //=> [
// {name: 'Alabama', pop: 4863300}
// {name: 'Alaska', pop: 741894},
// {name: 'Arizona', pop: 6931071},
// ...]
This would entail changes to the code above to work with the pop property of these objects, but it's probably more robust.
If your pop and state looks like:
var state = ['state1', 'state2', ...];
var pop = ['state1 pop', 'state2 pop', ...];
Then first of all, avg is already wrong. sum's value is running along with the loop turning avg's formula into sum as of iteration / array length instead of sum of all pops / array length. You should calculate the average beforehand. array.reduce will be your friend.
var average = pop.reduce(function(sum, val){return sum + val;}, 0) / pop.length;
Now for your filter operation, you can:
Zip up both arrays to one array using array.map.
Filter the resulting array with array.filter.
Finally, loop through the resulting array using array.forEach
Here's sample code:
var states = ['Alabama', 'Alaska'];
var pop = [4863300, 741894];
var average = pop.reduce(function(sum, val){return sum + val;}) / pop.length;
console.log('Average: ' + average);
states.map(function(state, index) {
// Convert 2 arrays to an array of objects representing state info
return { name: state, population: pop[index] };
}).filter(function(stateInfo) {
console.log(stateInfo);
// Filter each item by returning true on items you want to include
return stateInfo.population < average;
}).forEach(function(stateInfo) {
// Lastly, loop through your results
console.log(stateInfo.name + ' has ' + stateInfo.population + ' people');
});

JavaScript database correlation

I've been trying to 'correlate' between user picked answers and an object property name so that if the two matches then it will display what is inside.
My program is a recipe finder that gives back a recipe that consists of the ingredients the user picked.
my code currently looks like:
//property are the ingredients and the value are the recipes that contain those ingredients. The map is automatically generated
``var map = {
"pork" : [recipe1, recipe2, ...],
"beef" : [],
"chicken" :[],
}
//this gets the user pick from the dom
var cucumber = specificVegetable[7];
var lemon = specificFruits[0];
//Then this code finds the intersection of the recipe(recipes that use more than one ingredients)
function intersect(array1, array2)
{
return array1.filter(function(n) {
return array2.indexOf(n) != -1
});
}
var recipiesWithLemon = map["lemon"]; **// makes the lemon object is map**
var recipiesWithCucumber = map["cucumber"]; **// makes the cucumber object in map**
//Here is where I am stuck
function check(){
var both = intersect(recipiesWithLemon, recipiesWithCucumber);
if ( cucumber.checked && lemon.checked){
for (var stuff in map){
if(stuff="cucumber" && stuff="lemon"){
return both;
}
}
}
}
check();
so basically what I tried to do was I made my intersect and then if user pick is lemon and cucumber then look at the properties in the map object. if the name of the property equals to the exact string then return both. That was the plan but the code does not work and I'm not sure how to fix it.
My plan is to write code for every possible outcome the user may makes so I need to find the correlation between the user pick and the map which stores the recipe. I realize this is not the most effective way but I'm stumped on how to do it another way.
Thanks for the help.
Im using the open source project jinqJs to simplify the process.
I also changed your map to an array of JSON objects. If you must have the map object not as an array, let me know. I will change the sample code.
var map = [
{"pork" : ['recipe1', 'recipe2']},
{"beef" : ['recipe3', 'recipe4']},
{"peach" :['recipe5', 'recipe6']},
{"carrot" :['recipe7', 'recipe8']}
];
var selectedFruit = 'peach';
var selectedVeggie = 'carrot';
var selections = [selectedFruit, selectedVeggie];
var result = jinqJs().from(map).where(function(row){
for(var f in row) {
if (selections.indexOf(f) > -1)
return true;
}
return false;
}).select();
document.body.innerHTML += '<pre>' + JSON.stringify(result, null, 2) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>

Categories

Resources