I have a multidimensional array, where I'd like to check if a value is in it.
I tried the code below but it didn't work as intended
How do i check if username is in my multidimensional array?
let matrix = [
['Lol'],
['MyName'],
['Matrix']
];
let username = prompt('Enter Username')
if (matrix.includes(username)) {
alert('YESSS')
} else {
alert('no')
}
console.log(username)
There are a variety of JavaScript idioms to perform this task.
One option is to flatten the array before running include such as the example Hassam Imam posted.
matrix.flat().includes(username)
Issues will arise however depending on how much data is stored in the multidimensional array.
Another option would be to what Konrad Linkowski suggested and leverage some.
matrix.some(array => array.includes(username))
This has a performance increase as it will stop after finding the first case that matches the provided criteria, but the result is boolean. If you just want to know if the value exists I would recommend this solution.
If you wish to know where in the matrix an element is you will want to use find instead of some as it will provide you the index in which it was found.
matrix.find(arr => array.includes(username));
Though this could get quite complex depending on how many dimensions the array has.
Let me know if you have any questions or would like to stub out what this solution may look like.
I am currently working on a "crowdsourced" average value calculator. The idea is to show a picture to people and ask them to guess the age of the person. Once they entered the value, I want to show them the average age the person was given.
Here is what I want to do exactly :
Put a form online and ask people to put on a value
Store the data entered
Return the mean value people put there
Calculate the standard deviation so that people cannot put a value too high or too low compared to what others put. That means the average value shown will be more accurate this way.
I am looking for the fastest way to do it, and here is what I thought about :
Store the data in an SQL table and return the mean value through the AVG() function..but then, how would I calculate the Std. Dev ?
Store the data in a txt file and use javascript to convert it to an array do the calculations.
But if I get like 20,000 different values, it might be slow to do either way. ?
I am quite a beginner in programming and what I propose might seem ridiculous...feel free to tell it to me !
Thank you all.
SQL Server has STDEV (from 2005 onwards) so SQL sounds good for you.
Returns the statistical standard deviation of all values in the
specified expression. May be followed by the OVER clause.
Syntax
STDEV ( [ ALL | DISTINCT ] expression )
Arguments
ALL
Applies the function to all values. ALL is the default.
DISTINCT
Specifies that each unique value is considered.
expression
Is a numeric expression. Aggregate functions and subqueries are not permitted. expression is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.
I am trying to create a fairly complex system for my website. I want to be able to write some pseudo like code and then parse it to make it do something in my back-end.
My data is inside two $.each loops as this is an Object of data with multiple levels to it.
For instance, I want to take a string like this:
"<!this!> == <!PropertyStreetNumber!>"
Then how I would like for the above code to executed is this:
FormData[parentKey][this] == FormData[parentKey]["PropertyStreetNumber"]
Thanks for any help!
Here's some of my code, the code where this would need to go in (see commented area)
http://jsbin.com/liquvetapibu/1/
Is there any restriction not to use regular expressions on JavaScript?
You could do something like this:
var myString = "<!this!> == <!PropertyStreetNumber!>";
var aux = /<!(.*?)!> == <!(.*?)!>/.exec(myString);
The value of aux will be an array with 3 elements:
The string that was tested.
The first element within <! !>
The second element within <! !>
Then it would depend on what the content on each one is: in your example this is an object, while you seem to use PropertyStreetNumber as a string (maybe a typo?). If you want to use it as an object, you will have to use eval() (e.g.: eval(aux[1])) while if you want to use it as a string, you can use it directly (e.g.: aux[2]).
Conceptually, the first thing you would need to do is determine the type of statement you are working with. In this case, a comparison statement. So you need a regex statement to filter this into a "statement type".
Once you do that, you can figure out what the arguments are. So you create a regex to pull out the arguments on each side of the operator.
Next, the strings that represent action code items need to be parsed. The this argument is actually an object, whereas "PropertyStreetNumber" is a string. You've got to be able to determine which is which. Then you can filter that into a function that has been created specifically to handle those statements types.
If at all possible, I would try to avoid the use of eval(). You can get into trouble with it.
you could try with
var beg = str.indexOf("== <!") + 5;
to find the index of the beggining and then slice counting the chars from beginning like
str.slice(beg, -2);
and from there build the rest.
couldnt that work?`
For a school project I need to make a game in C. However, since I'm much more fond with javascript + js can give a easy visual implementation, I decided to write my game in js before in c, to get my structure right. That's why my code's so weirdly looped.
Now, the issue is that I have a switches[] array that has the switches being pressed (1/0). I want to compare this to another array, oldArray[]. Now, when comparing, they are both ALWAYS the same for some reason, and I just can't find it. Here's a full sample on jsfiddle.net. The issue is in the memory() function. This line isn't working properly:
if (switches[i] == 1 && oldArray[i] == 0 && guessedArray[i] == 8 && i != oldtouch) {...}
because switches[] always seems to be equal to oldArray[].
In the fiddle, press Start and check the consle output after clicking some buttons.
They are equal, because when the assignment statement oldArray = switches is executed, both variables point to the same underlying object in memory.
To copy all the values from one array to the other, without having them point to the same object, do oldArray = switches.slice(0)
See this for further discussion: Copying array by value in JavaScript
I'm using Jorn Zaefferer's Autocomplete plugin on a couple of different pages. In both instances, the order of displayed strings is a little bit messed up.
Example 1: array of strings: basically they are in alphabetical order except for General Knowledge which has been pushed to the top:
General Knowledge,Art and Design,Business Studies,Citizenship,Design and Technology,English,Geography,History,ICT,Mathematics,MFL French,MFL German,MFL Spanish,Music,Physical Education,PSHE,Religious Education,Science,Something Else
Displayed strings:
General Knowledge,Geography,Art and Design,Business Studies,Citizenship,Design and Technology,English,History,ICT,Mathematics,MFL French,MFL German,MFL Spanish,Music,Physical Education,PSHE,Religious Education,Science,Something Else
Note that Geography has been pushed to be the second item, after General Knowledge. The rest are all fine.
Example 2: array of strings: as above but with Cross-curricular instead of General Knowledge.
Cross-curricular,Art and Design,Business Studies,Citizenship,Design and Technology,English,Geography,History,ICT,Mathematics,MFL French,MFL German,MFL Spanish,Music,Physical Education,PSHE,Religious Education,Science,Something Else
Displayed strings:
Cross-curricular,Citizenship,Art and Design,Business Studies,Design and Technology,English,Geography,History,ICT,Mathematics,MFL French,MFL German,MFL Spanish,Music,Physical Education,PSHE,Religious Education,Science,Something Else
Here, Citizenship has been pushed to the number 2 position.
I've experimented a little, and it seems like there's a bug saying "put things that start with the same letter as the first item after the first item and leave the rest alone". Kind of mystifying. I've tried a bit of debugging by triggering alerts inside the autocomplete plugin code but everywhere i can see, it's using the correct order. it seems to be just when its rendered out that it goes wrong.
Any ideas anyone?
max
EDIT - reply to Clint
Thanks for pointing me at the relevant bit of code btw. To make diagnosis simpler i changed the array of values to ["carrot", "apple", "cherry"], which autocomplete re-orders to ["carrot", "cherry", "apple"].
Here's the array that it generates for stMatchSets:
stMatchSets = ({'':[#1={value:"carrot", data:["carrot"], result:"carrot"}, #3={value:"apple", data:["apple"], result:"apple"}, #2={value:"cherry", data:["cherry"], result:"cherry"}], c:[#1#, #2#], a:[#3#]})
So, it's collecting the first letters together into a map, which makes sense as a first-pass matching strategy. What i'd like it to do though, is to use the given array of values, rather than the map, when it comes to populating the displayed list. I can't quite get my head around what's going on with the cache inside the guts of the code (i'm not very experienced with javascript).
SOLVED - i fixed this by hacking the javascript in the plugin.
On line 549 (or 565) we return a variable csub which is an object holding the matching data. Before it's returned, I reorder this so that the order matches the original array of value we were given, ie that we used to build the index in the first place, which i had put into another variable:
csub = csub.sort(function(a,b){ return originalData.indexOf(a.value) > originalData.indexOf(b.value); })
hacky but it works. Personally i think that this behaviour (possibly coded more cleanly) should be the default behaviour of the plugin: ie, the order of results should match the original passed array of possible values. That way the user can sort their array alphabetically if they want (which is trivial) to get the results in alphabetical order, or they can preserve their own 'custom' order.
What I did instead of your solution was to add
if (!q && data[q]){return data[q];}
just above
var csub = [];
found in line ~535.
What this does, if I understood correctly, is to fetch the cached data for when the input is empty, specified in line ~472: stMatchSets[""] = []. Assuming that the cached data for when the input is empty are the first data you provided to begin with, then its all good.
I'm not sure about this autocomplete plugin in particular, but are you sure it's not just trying to give you the best match possible? My autocomplete plugin does some heuristics and does reordering of that nature.
Which brings me to my other answer: there are a million jQuery autocomplete plugins out there. If this one doesn't satisfy you, I'm sure there is another that will.
edit:
In fact, I'm completely certain that's what it's doing. Take a look around line 474:
// loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
/* some code */
var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] )
and so on. So, it's a feature.