Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to find the most efficient/fastest way of checking if a string belongs in an array in both Java and JavaScript. For example, I want to find if the string "=" belongs in the array {"+", "-", "=", "*", "/", "!"}
A way to do it in Java is(omitting the main method)
String[] symbols = {"+", "-", "=", "*", "/", "!"};
String equalTo = "=";
for(String i: symbols) {
if(equalTo.equals(i)) {
System.out.print(equalTo + " belongs to symbols.");
}
}
I would like to know if there is a single method which does this work for me in either Java and JavaScript.
The reason I am asking this in both languages is that I want to see if it is easier in Java or JavaScript.
Answers for your question in JavaScript: How do I check if an array includes an object in JavaScript?
E.g. If you search for full match you can use:
["=", "+", "-"].indexOf("=") // => 1
The most efficient way to see if a string is in a collection of strings, is when this collection is already hashed. For example, if you have a HashSet<String> in Java, you can just use the .contains(String) method, which runs in O(1).
If your collection is stored as a ArrayList<String> or array, it takes O(n) time to check if a string is in the collection (also with the .contains(String) method).
Turning a list or array into a set takes O(n) time, but takes longer than checking if a single element is in the list.
So, in conclusion:
If you only want to check for one element if it's in the collection, just iterate over the list that you apparently already have, and check if the element is in the list. For an array, in Java simply use Arrays.asList(symbols).contains(equalTo) and in JavaScript use symbols.contains(equalTo)
If you want to check for a lot of elements whether they are in the collection, then it's better to turn the collection into a set first. In Java, do something like
HashSet<String> set = new HashSet<String>();
set.addAll(Arrays.asList(symbols));
after which you can do set.contains(equalTo).
For JavaScript, that's a little more annoying, but the first thing off the top of my head is like this:
var set = Object.create(null);
for (var i in symbols) {
set[i] = true;
}
Then, you can check if checkTo in set.
Sorry for long answer, but you asked for efficiency right?
In Java you can use Arrays.asList(yourArray).contains(yourValue). If you use jQuery you can use $.inArray(yourValue, yourArray).
The "best" way to do it really depends on the number of values to match against and how often you need to do it.
If the list is long, and you do it often, you'd be better served by creating a set/map/associate-array for fast lookup, or sort the list of values and perform a binary search. In Java, that would be Set<String> or Arrays.binarySearch().
However, in your case the list is short, so a sequential search like you're doing is fine.
But in addition to that, your values are all single-character, so there is a solution that just happens to be the exact same solution for both Java and JavaScript: indexOf()
In Java:
if ("+-=*/!".indexOf(value) != -1) {
// found
}
In JavaScript:
if ("+-=*/!".indexOf(value) != -1) {
// found
}
Eerie, huh?
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Is there a way to access all the object instances starting with a common string.
Example: I have instances named button64, button223, button856471, button229846, etc. I have no control over how these instances are named. I want to push all these in an array.
I am not creating these objects, I just have to write a javascript which sits in this HTML page and collects all the object instances starting with the string 'button'.
The purpose is to reach out to a desired object out of these and change the visual element.
Also, the solution has to be compatible with IE8. Any ideas about how should I iterate?
If you can use jQuery, you could write:
var buttonsArray = [];
$("div").each(function() {
var id = $(this).attr("id");
if (id && id.indexOf("button") == 0) {
buttonsArray.push($(this));
}
});
You can use regular expressions to find any expression matching the pattern. Using the match method, every instance of the pattern is returned as an array.
var str = document.getElementById("sample");
var arr = string.match(/button[\d]*/g);
The regular expression on line two will match any result that has "button" and will stop once it encounters a character afterwards that is not a digit.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What is the difference between the following and which is the preferred?
Option 1
var object = {
'propertyName':'propertyValue'
}
Option 2
var object = {
"propertyName":"propertyValue"
}
Option 3
var object = {
propertyName:'propertyValue'
}
I realize option 2 is true JSON syntax.
They're all equivalent in Javascript.
Javascript makes no distinction between using single and double quotes when writing a string.
When specifying the keys of an object literal, you need to quote it if it's not a valid identifier, or if it's a reserved keyword. Otherwise, you can write it as a string, using either quotes.
Preference is a personal style question. Most programs are written using the last syntax, but you can occasionally run into problems. For instance, Internet Explorer rejects class: "value" as a syntax error because class is a reserved word, so it needs to be quoted. I frequently encounter this problem when using jQuery to create elements, e.g.
$("<div>" {
id: "foo",
class: "fooClass"
});
will cause an error in IE.
None of these are JSON. They are all varying versions of JavaScript code which uses JavaScript's literal syntax for object creation. All accomplish the same (depending on the chars or keywords you're using in the property name) and it is up to you which you choose (though you should be consistent).
JSON is a platform independent serialization scheme for transporting data between platforms/environments/processes. Its syntax consists of a subset of JavaScript's literal syntax. JSON is always a string.
In the former, it's your choice. In JSON, the spec is very clear that the style used in your second example would be used when writing JSON (though, again, your second example is not actually JSON). JSON serializing any of those variables would produce the following in a string:
{"propertyName": "propertyValue"}
This is true on any platform which supports JSON.
If the JavaScript code is being run in a browser, there is no difference.
The "preferred" syntax is largely an opinion, but I see property names without quotes more often than not.
Using quotes does allow you to use non alpha numeric characters in property names when defining an object in JSON:
var config = {
"foo.url": "/foo",
"foo.timeout": 3000,
"foo^10": 100
};
config["foo.url"];
I've used this before in a config object where I don't want deeply nested properties, but I do want a sudo namespacing scheme to the property names.
There is no difference between any of these syntaxes. You are free to use any of these if you are using this in javascript.
JSON is a bit different it's cross platform object literal. Programmers mistakenly don't create errorfull code, that's why it's syntax make it strictly use " quotes for keys.
So without quotes
{ "i-name" : "Some value" }
will be totally wrong, as it has hyphen in it.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have two comma separated lists, the first is a list of possible values, and the second is a list of "selected" values. I need to create a list of all of the items in the first list that do not exists in the second list.
I could just split the first list into an array and use a "for" to go through the list using a string_pos to see if the first list item is contained in the second, but I'm wondering if there is a more efficient way to accomplish this.
Thanks!!
You can filter the possible list.
if the lists are strings, split or match them to get arrays.
var possible=[1,2,3,4],
selected=[2,4];
var unchosen=possible.filter(function(itm){
return selected.indexOf(itm)==-1;
});
unchosen
/* returned value: (Array)
1,3
*/
If you are looking for the best possible way, this is what you have to do
Convert the list to be checked, to an object, in liner time. Because, objects are technically hashtables, which offer faster lookups O(1)).
Then, iterate over the first list and check if the current element is there in the object or not. If it is not there, add it to the result.
var list1 = [1, 2, 3], list2 = [1, 2], dict2 = {};
list2.forEach(function(item) {
dict2[item] = true;
});
var result = list1.reduce(function(prev, current) {
if (dict2.hasOwnProperty(current) === false) {
prev.push(current);
}
return prev;
}, [])
console.log(result);
Output
[ 3 ]
The first thing you want to do is definitely to split the two comma separated lists into arrays of strings. Assume that they are formatted fairly reasonably, you can do this with
possible_values = possible_string.split(/,\s?/) //split on commas with a possible space
selected_values = selected_string.split(/,\s?/)
If you are willing to use outside libraries, underscore.js has a perfect function for this. The operation you are describing is the set difference operator, which is the difference function in underscore.
The result you want is the return value of calling
_.difference(possible_values, selected_values)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'd like to determine the best practice for storing and retrieving a simple list into a single JSON key.
Let's assume I have 5 friends:
bob, joe, peter, susan, & tiffany
Say I've got a larger JSON collection that looks like this:
{
"title":"my title",
"description":"my description about this collection"
}
Now if I wanted to add this list of friends to my collection under the key "friends", I would probably structure it like this:
{
"title":"my title",
"description":"my description about this collection"
"friends":[
"bob",
"joe",
"peter",
"susan",
"tiffany"
]
}
One of the biggest challenges I've faced doing it this way is that you can't use some of the built in javascript or php array functions.
On the other hand, storing an unknown number of objects in a key:value paired array would be equally unmanageable.
If someone could explain best way to store a list of strings in JSON I'd be indebted. Are there easier ways to search and access the array data?
Store it in the most normalized format unless there is good reason to do otherwise. In this case I would argue an array/list is most appropriate. It's a homogenous collection of names.
As far as language support - learn it. Remember that JSON is only the text, but once in JavaScript (or PHP) objects, there should be appropriate collection searching:
var ar = ["a", "b", "c"]
var i = ar.indexOf("b") // -> 1
var b = ar[i]
alert(b) // -> "b"
Note that Array.indexOf was introduced in ECMAScript 5th edition. I recommend using a shim for older browsers.
Something like the following ought to work pretty well:
function checkIfFriends(json, friend) {
return json.friends.indexOf(friend) !== -1;
}
You can implement other search functions just as easily:
function findFriendsOf(people, friend) {
var found = [];
for(var i = 0; i < people.length; i++) {
if(people[i].indexOf(friend) !== -1) {
found.push(people[i]);
}
}
return found;
}
In general, the best way to store a list of monotyped objects is as an Array. This is what people generally expect it to be stored as and will make other people's lives easier when they have to maintain it.
While it's not optimum, you could store the elements in a string and use a regex, as in:
var src='joe,fred,bob,zebulon';
function hasMember(src,name){
var RE=new RegExp('(?:^|,)'+name+'(?:,|$)');
return RE.test(src);
}
src.split(',').forEach(function(name){
console.log(name+':'+hasMember(src,name));
});
which prints:
joe:true
fred:true
bob:true
zebulon:true
and for console.log('rob:'+hasMember(src,'rob')) prints:
rob:false
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Note: This is a continuation of another question that I decided were two separate issues that need to be solved. I'm also currently not sure of how exactly to phrase this question, so I will try my best and when I get more clarity I will rephrase my question for future reference.
I'm writing two basic jQuery plugins, $.fn.query and $.fn.build, that sort an array, and create html code to insert into a document, respectively. I'm currently testing it with Vimeo video ID's that I will display videos with.
$.fn.build has three parts. First it wraps every array item with individual containers, the builds them into rows (problem area), then lastly it wraps everything in a container. (every part of this is optional).
Specifically the problem comes from this line: $(tmp).add(newRow); although it is valid javascript.
if ( options.splitBy !== undefined && options.wrapRow !== undefined ) {
var tmp = $([]),
newRow = function(i) {
$(build.splice( i, i + options.splitBy )).wrapAll( options.wrapRow ).parent();
};
for (var i = 0, l = build.length, a = options.splitBy; i < l; i += a) {
$(tmp).add(newRow);
}
build = tmp;
console.log(build);
}
See: http://jsbin.com/upatus/2/edit
I am quite sure that you want to use the function, instead of adding the function itself. Also, you will want to use the same tmp object all over the time, instead of wrapping it into a new jQuery instance and not adding to the original one. Try
tmp.add(newRow(i));
BTW: If you want to build an array, you should use
var tmp = [];
and
tmp.push(…);
Now I've looked at the code from the other question. Both answers are correct, and contain some valid points:
splice is an Array function on jQuery's prototype, and returns an array. (You have fiexd this now)
Your query method returns an array, but should return a jQuery instance for chaining
Your build variable was not initialized, but used
You should really choose whether you want to use arrays or jQuery objects internally in your function, and not mix them.
BTW, you should rename your functions to more descriptive names. "build" and "query" are very vague and may collide with other plugins.