For example:
var array = [1,2,3,4];
if( 5 > array ){
alert('ok');
}
Can i do this in javascript ?
Well, it's pretty simple, use .indexOf() (MDN)
var text ="abc";
var array = ['abc', 'def'];
if(array.indexOf(text) !== -1){
alert('ok');
}
Can I do this in JavaScript?
I don't know. Try it.
An if statement evaluates a single expression. If you want to evaluate multiple conditions, which is the case here, you have to write the multiple conditions.
if( 5 > array[0] && 5 > array[1] && 5 > array[2] && 5 > array[3]) {
alert('ok');
}
Since that is not going to work well if you don't know the number of elements in array in advance, you could write a loop, looking for failing cases:
let ok = true;
for (const i = 0; i < array.length; i++) {
if (5 > array[i]) continue;
ok = false;
break;
}
if (ok) alert('ok');
It turns out, though, that arrays have a built-in method to check to see if some condition holds for all elements, so we can write:
if (array.every(elt => 5 > elt)) alert('ok');
If you wanted to check if an element(text) exists in the array, then this can be used
if(array.indexOf(text) !== -1){
alert('ok');
}
var array = [1,2,3,4,5]
var i = 0;
var num = 4;
for(i = 0;i < array.length;i++){
if(array[i] == num){
alert("OK")
}
}
This can also be used but using the indexOf() function will be much faster
Related
I try to draw a graph from tens of thousands points, but because this number is so big i need to reduce it. Many of them have duplicates. I tried to reduce the number using this:
var array=_.reject(data,function(object,i){
return i>0 && (data[i-1].a === object.a && data[i-1].b===object.b && data[i-1].c===object.c);
});
How can i modify this function, or to create a new one, in order to keep first and last value considered duplicate. Those are different by another attribute 'd' which represent a time stamp.
//return filtered points, compareFunction for sorting, equalFunction for
//removing points
function removeDuplicate(data,compareFunction,equalFunction) {
data.sort(function(pointa, pointb) {
var compare = compareFunction(pointa,pointb);
return compare;
});
var arr = new Array();
var prev = new Object();
var index = 0;
for (var i = 0; i < data.length; i++) {
if (i == 0 || !(equalFunction(prev,data[i]))) {
arr[index++] = data[i];
prev = data[i];
}
}
return arr;
}
function compareFunction(pointa,pointb){
return (pointa.a + pointa.b + pointa.c) - (pointb.a + pointb.b + pointb.c);
}
function equalFunction(pointa,pointb){
return pointa.a == pointb.a && pointa.b == pointb.b && pointa.c == pointb.c;
}
example - https://jsfiddle.net/8xu4Lwp2/
The simplest way to eliminate duplicates from an array in JavaScript is to cast it as a Set and then back to an Array. Sets don't store duplicates.
// not sure why setArr isn't logging, it does in Opera console.
arr=[1,1,2,2,3,3];
console.log(arr);
setArr=new Set(arr);
console.log(setArr);
newArr=[...setArr];
console.log(newArr);
Cool solution:
var unique = Array.from(new Set(arrayWithDuplicatedValue));
I need to create a function to check if all the letters in the second string of a two string array are present in the first string. The function I wrote seems to work for most of the examples I tried with it but ["hello" , "hey"] returns true despite there not being a y in hello and I don't understand why.
Here's my code:
function mutation(arr) {
arr[0] =arr[0].toUpperCase().split("");
arr[1] =arr[1].toUpperCase().split("");
for(i=0;i<arr[1].length;i++){
if(arr[0].indexOf(arr[1][i])>=0){
return true;
} else {return false;}}}
mutation(["hello", "Hey"]);
You are returning true even if one character is matched ,Try below code it checks if all characters are present or not
function mutation(arr) {
arr[0] = arr[0].toUpperCase().split("");
arr[1] = arr[1].toUpperCase().split("");
var count = 0;
for (i = 0; i < arr[1].length; i++) {
if (arr[0].indexOf(arr[1][i]) >= 0) {
count++;
}
}
return count === arr[1].length
}
mutation(["hello", "Hey"]);
here is one more efficient solution, it works only for lowercase letters.
(function(){
function charCode(str, i){
return str.charCodeAt(i) - 97;
}
function isMutation(a,b){
const aArr = new Uint8Array(26);
const bArr = new Uint8Array(26);
let i=0;
let index = 0;
while(i<a.length){
++aArr[charCode(a, i)];
++i;
}
i = 0;
while(i<b.length){
++bArr[charCode(b, i)];
++i;
}
i = 0;
while(i < 26){
if(!(aArr[i]===0 && bArr[i]===0 || aArr[i]>0 && bArr[i]>0)){
return false
}
++i;
}
return true;
}
console.assert(isMutation('hello', 'oleh') === true);
console.assert(isMutation('hello', 'hey') === false);
})();
you can also compare sum of uniq chars in the both arrays, but in this case you have to add each letters only once.
I would recommend using one of the code solutions suggested by user georg at Remove Duplicates from JavaScript Array.
For example, the function below could be used to sort each array (arr[0] and arr[1]) and remove duplicates.
Credit to user georg at the link above.
function uniq(a) {
return a.sort().filter(function(item, pos, ary) {
return !pos || item != ary[pos - 1];
})
}
Once you have sorted/removed duplicates, you can test to see if the two returned strings are equal or not.
Hello => EHLO, and Hey => EHY
EHLO !== EHY
I was been asked in an interview to code for the following scenario.
var ele = [2,5,4,8,4,9].second();
If the above statement is written in javascript it ele should contain second highest element from that array. In this case it should contain 8.
how do you write the code for this? I assume we will have to write a function second()
but how do we call make sure it takes the array as that parameter?
Please help me with this. Thank You in advance.
That should get you started
Array.prototype.second = function() {
var biggest = -Infinity;
var second = -Infinity;
for (var i = 0; i < this.length; ++i) {
if (this[i] > biggest) {
second = biggest;
biggest = this[i];
} else if (this[i] < biggest && this[i] > second) {
second = this[i];
}
}
return second;
};
You should include error handling and there's plenty of room to optimize this solution.
Add a method to the Prototype of the Array Object.
Array.prototype.second = function() {
// Your logic here
}
I have a dictionary like:
a = {"staticData":['----','Blue','Green'], "inData":['Indatahere','----','----']}
How can I find that if the dictionary contains "----", in any of the key's values.
Any Javascript function?
EDIT:
What if the case is like this?
a = {"staticData":[], "inData":['Indatahere','----','----']}
It's giving this Error:
TypeError: a[elem].indexOf is not a function
Here is the code:
var a = {"staticData":['----','Blue','Green'], "inData":['Indatahere','----','----']};
for(var key in a){
var value = a[key];
for(var i=0; i<value.length; i++){
if(value[i] == '----') alert("Found '----' in '" + key + "' at index " + i);
};
}
EDIT: Changed iteration over array to normal way after comment.
Use indexOf to search each array in the a object:
for (elem in a)
{
if (a[elem].indexOf("----") != -1)
alert('---- found at ' + a[elem]);
}
EDIT
For this error: TypeError: a[elem].indexOf is not a function the browser possibly considers an empty element to be a non-string type; non-string type does not have an indexOf method.
This code checks the length of the array element (if the element is empty before interpreting the indexOf function.
for (elem in a)
{
if (a[elem].length > 0 && a[elem].indexOf("----") != -1)
alert('---- found at ' + a[elem]);
}
If you wish to support IE < 9, see this post to conditionally add a indexOf definition to the Array object. The post also mentions a Jquery alternative.
The SO post mentioned above lists this Mozilla version of indexOf function.
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
If you know exactly the nesting level of your value, then a quick solution (as suggested in other answers) is possible.
However, if you need a deep traversal search, you're gonna need a recursive version of the solutions, something like:
function FindTraverse(data, match)
{
for (var prop in data)
{
if (!data.hasOwnProperty(prop)) continue;
if (data[prop] == match) return true;
if (typeof data[prop] == 'object' && FindTraverse(data[prop], match)) return true;
}
return false;
}
Examples:
FindTraverse({a:'Foo',b:'Bar'}, 'Bar') // true
FindTraverse(['Foo','Bar'], 'Bar') // true
FindTraverse([{name:'Foo'},{name:'Bar'}], 'Bar') // true
FindTraverse({a:{name:'FooBar'},b:'Bar'}, 'FooBar') // true
However, if you're looking for a more thorough solution, use a framework like jsTraverse
Use Object.getOwnPropertyNames().
You have to write two nested loops. With Object.getOwnPropertyNames you are accessing an array which consists of property names of an object. You will then need to loop over the value of those properties and identify the correct element within this second array.
a = {"staticData":['----','Blue','Green'], "inData":['Indatahere','----','----']}
props = Object.getOwnPropertyNames(a);
for (i=0;i < props.length;i ++) {
for (z = 0; z < a[props[i]].length; z ++) {
//console.log(a[props[i]][z])
if ( (a[props[i]][z]) == '----') {
console.log("I have found an item with ----")
};
}
}
How can I determine if a string contains one of the values from an array?
For example:
var a = ["abc","def","ghi"];
var s = "jskljfdkljflkjk abc jskfdjklsj";
for(var i=0;i<a.length;i++){
if(/a[i]/.test(s)) alert(1);
}
This obviously doens't work... I know it's very possible though hahaha
Your syntax for creating the regular expression is incorrect. That regex will only return true for a string "ai". And you're testing the regular expression against the array. I think what you meant to write is:
if(RegExp(a[i]).test(s)) alert(1);
You would probably be better off just using indexOf in this case. It'll be faster and you won't need to escape any characters.
var a = ["abc","def","ghi"],
s = "jskljfdkljflkjk abc jskfdjklsj";
for(var i = 0, l = a.length; i < l; i++)
if(s.indexOf(a[i])+1) alert('string s contains a value from array a');
function doesStringContainElementFromArray(str, arr)
{
for ( var i=0; i<arr.length; i++)
{
if ( str.indexOf(arr[i]) != -1 )
return true;
}
return false;
}
Just use the "RegExp" function/constructor (if you really need regexps)
if (RegExp(a[i]).test(a)) {
alert(1);
}
if you don't, just use .indexOf
if (s.indexOf(a[i]) != -1) {
alert("a[i]="+a[i]+" is matched in " + s);
}
You can use search method of JavaScript
var a = ["abc","def","ghi"];
var s = "jskljfdkljflkjk abc jskfdjklsj";
for(var i=0;i<a.length;i++){
if(s.search( a[i] ) != -1)
{
alert("found");
}
}