try to not add the elements already in the array - javascript

function neighbor(color_indices) {
var neighbor_face = [];
var neighbor_index_temp = [];
//initialize to the given length
var color_indices_length = color_indices.length;
for (var i = 0; i < color_indices_length; i++) {
if (color_indices[i] % 2 == 0 ) {
if (color_indices[i] % 10 == 8) {
neighbor_index_temp[0] = (color_indices[i]) + 1;
neighbor_index_temp[1] = (color_indices[i]) - 17;
neighbor_index_temp[2] = (color_indices[i]) - 19;
//check if it is in the array
for (var k = 0; k < 3; k++){
if ($.inArray(neighbor_index_temp[k],color_indices) != -1){
color_indices.push(neighbor_index_temp[k]);
}
}
The input : color_indices would be an array of the global variable. I am trying to push neighbor_index_temp of only new to the color_indices. I tried to implement $.inArray but it doesn't seem to work. Any suggestions?
Thanks!

You can use indexOf to achieve this. Ie.
if(color_indices.indexOf(neighbor_index_temp[k]) == -1) {
// value neighbor_index_temp[k] is not in color_indices array
}
Edit : $.inArray might do the same as indexOf, in this case you might want to change '!= -1' to '== -1'

Related

checking if a substring of length 5 is in another string (refactored)

I'm trying to check if string b contains any 5-character substring a.
This works, but is a little messy:
var a = "1eabcde";
var b = "12abcde12fg";
for(var i=0; i<a.length; i++){
for(var j=i;j<a.length-i;j++){
if(a.charAt(j) == b.charAt(i) && a.charAt(j+1) == b.charAt(i+1) && a.charAt(j+2) == b.charAt(i+2) && a.charAt(j+3) == b.charAt(i+3) && a.charAt(j+4) == b.charAt(i+4)){
alert("ya");
}
}
}
Are there any other cleaner options?
You can use substring and indexOf:
var a = "1eabcde";
var b = "12abcde12fg";
for (var i = 0; i <= a.length - 5; i++) {
if (b.indexOf(a.substring(i, i + 5)) >= 0) {
alert("ya");
}
}
(You could use a.substr(i, 5) instead of a.substring(i, i + 5). Those two calls behave identically.)
Note that if you loop from 0 to a.length (as in your original code), then all suffixes of a of length 5 or less will be searched for in b.
In one respect, this code does not behave the same as your original: it will alert only once for each matching substring of a, regardless of how many times that particular substring may occur in b. Thus, if a = 'abcde' and b = '01abcde23abcde45, your original code would pop up two alerts (one for each occurrence of 'abcde'), whereas the above will only alert once. If you want the original behavior, change the if to a while like this:
for (var i = 0; i <= a.length - 5; i++) {
var j = -1;
while ((j = b.substring(j+1).indexOf(a.substr(i, 5))) >= 0) {
alert("ya");
}
}
This is the cleanest approach :
var a = "1eabcde";
var b = "12abcde12fg";
for (var i = 0; i <= a.length - 5; i++) {
if(b.indexOf(a.substr(i, 5)) > -1) {
alert("ya");
}
}

How to set an empty array in a for loop in JavaScript in case the array to loop is undefined?

I want to loop over an array called children which may or may not be defined.
Currently I'm doing this:
var i;
var foo = {/*"children": ["1","2","3","4"]*/};
for (i = 0; i < [foo.children || []][0]. length; i += 1) {
console.log("hello")
}
This works correctly, because in case children is undefined, [foo.children || []][0] ends up being [[]] whose first element is an empty array [].
Question:
Is there any way to leave away the outer array?
I don't want to use an if-clause testing for children, just modify the array.
One way would be:
for (i = 0; i < foo.children.length || [].length; i += 1) {
console.log("hello")
}
but I'm looking for other alternatives if exist.
Thanks
EDIT:
Here is a jsperf on all variants. Interesting...
var len = foo.children ? foo.children.length : 0;
for (i = 0; i < len; i++) {
...
}
Use parenthesis instead of that one-item-array:
for (i = 0; i < (foo.children || []).length; i += 1) {
or move it further outside:
for (i = 0; foo.children && i < foo.children.length; i += 1) {
which is very near to
if (foo.children) for (i = 0; i < foo.children.length; i += 1) {
which would indeed be the cleanest way. There's nothing wrong with an if-statement.
EDIT: According to comments on other answers the OP wants terse, but jsLint appropriate code. Here it is:
var i, c, foo = {}, console;
for (i = 0, c = foo.children; i < (c && c.length); i += 1) {
console.log("hello");
}
I will leave the other possibilitis here for people who don't have as strict requirements as the OP does.
You can use the && operator:
for (i = 0; i < (foo && foo.children && foo.children.length); i += 1) {
console.log("hello")
}
If there is a chance that foo is not defined at all, then you need something slightly worse:
for (i = 0; i < ((typeof foo === 'object') && foo.children && foo.children.length); i += 1) {
console.log("hello")
}
Or if you're sure that foo is an object, you can skip the first check:
for (i = 0; i < (foo.children && foo.children.length); i += 1) {
console.log("hello")
}
Another possible way:
for (i = 0; foo.children && i < foo.children.length; i += 1)
You could add a condition checking the existence of the array to your for loop like this:
for (i = 0; (typeof foo.children != 'undefined') && (i < foo.children.length); i++) {
// do something
}
/edit:
OK, others were a bit faster than me, and foo.children is a nice alternative to typeof foo.children != 'undefined' ;)
Why not using a function to hide all these dirty statements?
function each(array, fn) {
if (array) {
var i = -1;
while (++i < array.length) {
if (fn(array[i]) === false) return;
}
}
}

Insert dashes into a number

Any ideas on the following? I want to input a number into a function and insert dashes "-" between the odd digits. So 4567897 would become "456789-7". What I have so far is to convert the number into a string and then an array, then look for two odd numbers in a row and use the .splice() method to add the dashes where appropriate. It does not work and I figure I may not be on the right track anyway, and that there has to be a simpler solution.
function DashInsert(num) {
var numArr = num.toString().split('');
for (var i = 0; i < numArr.length; i++){
if (numArr[i]%2 != 0){
if (numArr[i+1]%2 != 0) {
numArr.splice(i, 0, "-");
}
}
}
return numArr;
}
The problem is you're changing the thing you're iterating over. If instead you maintain a separate output and input...
function insertDashes(num) {
var inStr = String(num);
var outStr = inStr[0], ii;
for (ii = 1; ii < inStr.length; ii++) {
if (inStr[ii-1] % 2 !== 0 && inStr[ii] % 2 !== 0) {
outStr += '-';
}
outStr += inStr[ii];
}
return outStr;
}
You can try using regular expressions
'4567897'.replace(/([13579])(?=[13579])/g, '$1-')
Regex Explained
So, we find an odd number (([13579]) is a capturing group meaning we can use it as a reference in the replacement $1) ensure that it is followed by another odd number in the non-capturing positive lookahead ((?=[13579])) and replace the matched odd number adding the - prefix
Here is the function to do it:
function dashes(number){
var numString = '';
var numArr = number.toString().split('');
console.log(numArr);
for(i = 0; i < numArr.length; i++){
if(numArr[i] % 2 === 1 && numArr[i+1] % 2 === 1){
numString += numArr[i] + '-';
}else{
numString += numArr[i];
}
}
console.log(numString);
}
dashes(456379);
Tested and everything.
Edit: OrangeDog's answer was posted earlier (by nearly a full half hour), I just wanted to make an answer which uses your code since you're almost there.
Using another array instead of splicing into one you were looping through (this happens to return a string using join):
var num = 4567897;
function DashInsert(num) {
var numArr = num.toString().split('');
var len = numArr.length;
var final = [];
for (var i = 0; i < len; i++){
final.push(numArr[i]);
if (numArr[i]%2 != 0){
if (i+1 < len && numArr[i+1]%2 != 0) {
final.push("-")
}
}
}
return final.join("");
}
alert(DashInsert(num));
function dashInsert(str) {
var arrayNumbers = str.split("");
var newString = "";
for (var i = 0; i < arrayNumbers.length; i++){
if(arrayNumbers[i] % 2 === 1 && arrayNumbers[i + 1] % 2 === 1){
newString = newString + arrayNumbers[i] + "-";
} else {
newString = newString + arrayNumbers[i];
}
}
return newString;
}
var result = dashInsert("3453246");
console.log(result);

formatMoney function in Javascript doesn't work

I need a function which can transform the number 10000 to this number: 10.000.
So I tried the following:
function formatMoney(money){
var value = money.toString();
var l = value.length;
var new_value = 0;
new_value = new_value.toString();
if(l > 3){
var moneyarray = value.split('');
var u = 0;
for(i = l;i >= 0;i--){
if(u > 3){
u = 0;
new_value = "."+new_value;
}
new_value = moneyarray[i]+new_value;
u++;
}
}
return new_value;
}
And then call this:
formatMoney("10000");
But the result is
10.000undefined0"
What did I do wrong?
You're assigning the index counter to the length of the string;
var l = value.length;
...
for(i = l;i >= 0;i--){
And the down count starts with the length-index, which isn't present since arrays are zero-based. Subtract beforehand instead;
for(i = l;i >= 0;--i){
EDIT: Disregard this, I wasn't paying enough attention to the question.
If all you're looking to do is take numbers that are 4 digits or greater and put a dot in three digits from the right, you could give this a shot:
function formatMoney(money) {
var moneyString = money.toString();
var moneyLength = moneyString.length;
if(moneyLength < 4) {
return 0;
}
var dotIndex = moneyLength - 3;
return moneyString.substr(0, dotIndex) + "." + moneyString.substr(dotIndex);
}
Also, formatting your code in the post is good stuff. Indent it all by four spaces.
function formatMoney(money){
var value = money.toString();
var l = value.length;
var new_value = 0;
new_value = new_value.toString();
if(l > 3){
var moneyarray = value.split('');
for(var i = l-1;i >= 0;i--){
if((l-i)%3 === 0){
new_value = "."+new_value;
}
new_value = moneyarray[i]+new_value;
}
} else {
new_value = value;
}
return new_value;
}
A couple of things:
You were counting down with the wrong index (you were starting at l, instead of l-1)
You were not handling any value less than 1000
You don't need to use a counter variable u, you can just use modulo math to keep track of threes.
I cut off some parts:
function formatMoney(money) {
var value = money.toString();
var l = value.length;
var new_value = "";
if (l > 3) {
var u = 0;
for (i = l-1;i >= 0;i--) {
if (u == 3) {
u = 0;
new_value = "." + new_value;
}
new_value = value[i]+new_value;
u++;
}
}
return new_value;
}
You could do it like this:
function money(m) {
m = m.toString().split('');
for (var i = m.length - 3; i > 0; i -= 3)
m.splice(i,0,".");
return m.join('');
}
console.log(money(1000000)); // "1.000.000
See this JsBin

How to modify this function to return string instead of int

please take a quick look at this function that I have found on the web.
function longestCommonSubstring(string1, string2){
// init max value
var longestCommonSubstring = 0;
// init 2D array with 0
var table = Array(string1.length);
for(a = 0; a <= string1.length; a++){
table[a] = Array(string2.length);
for(b = 0; b <= string2.length; b++){
table[a][b] = 0;
}
}
// fill table
for(var i = 0; i < string1.length; i++){
for(var j = 0; j < string2.length; j++){
if(string1[i]==string2[j]){
if(table[i][j] == 0){
table[i+1][j+1] = 1;
} else {
table[i+1][j+1] = table[i][j] + 1;
}
if(table[i+1][j+1] > longestCommonSubstring){
longestCommonSubstring = table[i+1][j+1];
}
} else {
table[i+1][j+1] = 0;
}
}
}
return longestCommonSubstring;
}
It returns the length of the longest common substring as an int. Now to my question, is it possible to modify this function, so that it returns the actual string instead of just returning the length of the substring, I'm quite new at programming and thought that just modifying this secetion would help if(string1[i]==string2[j]){ push(string1[i]}, but it isn't that easy, because I don't want every single character that is the same in those 2 strings to be added in that array, only those that are exactly the same.
Thanks in advance =)
Well for minimal changes to the existing function you could declare a new variable:
var theCommonString = '';
Then in the middle of the function add a line after this existing one:
longestCommonSubstring = table[i+1][j+1];
that says something like:
theCommonString = string1.substr(i + 1 - longestCommonSubstring,
longestCommonSubstring);
(That i + 1 index may be a little off, I haven't bothered working it out carefully.)
Then at the end just return your new variable instead of the existing one.
Note that if there is more than one common sub string of the same length this will return the last one.
You can just store the whole common substring in the table instead of its length:
function longestCommonSubstring(string1, string2){
// init max value
var longestCommonSubstring = "";
// init 2D array with 0
var table = Array(string1.length);
for(a = 0; a <= string1.length; a++){
table[a] = Array(string2.length);
for(b = 0; b <= string2.length; b++){
table[a][b] = 0;
}
}
// fill table
for(var i = 0; i < string1.length; i++){
for(var j = 0; j < string2.length; j++){
if(string1[i]==string2[j]){
if(table[i][j] == 0){
table[i+1][j+1] = string1[i];
} else {
table[i+1][j+1] = table[i][j] + string1[i];
}
if(table[i+1][j+1].length > longestCommonSubstring.length){
longestCommonSubstring = table[i+1][j+1];
}
} else {
table[i+1][j+1] = 0;
}
}
}
return longestCommonSubstring;
}

Categories

Resources