How to do math with an array (add +1) - javascript

I have a value in an input like this:
7*7*0*0*32*17
I do a simple .split('*') to obtain the following arrays:
["7","7","0","0","32","17"]
Then I transform the arrays into numbers with .map(Number), so the arrays are now composed not of strings but numbers:
[7,7,0,0,32,17]
What interests me is the second 7. I use a .slice(1,2) in order to select it alone. Until that point, it works:
[7]
My problem is, I can't add +1 to transform the 7 into a 8. Instead, it returns 71.
Let's call the array of ["7","7","0","0","32","17"] -> "myArray" to simplify the whole stuff.
console.log(myArray);
var myArrayMapped = myArray.map(Number);
console.log(myArrayMapped);
var myArraySliced = myArrayMapped.slice(1,2);
console.log(myArraySliced);
var myArrayIncreased = myArraySliced + 1;
console.log(myArrayIncreased);
And here will be the results of the console.logs:
["7","7","0","0","32","17"]
[7,7,0,0,32,17]
[7]
71
Everything works as expected up until this line, which doesn't work:
var myArrayIncreased = myArraySliced + 1;
Note that my final goal is to put back the 8 inside the input, and reconstruct the array into one single string like below, so maybe there's a simplier and faster solution I haven't seen. Basically, a button will call a function to add +1 to the very specific part of value I want to select (the second "7"):
From:
7*7*0*0*32*17
To:
7*8*0*0*32*17
Thanks in advance. Note that I do not want to sum up all the arrays, nor push a new array among the ones I got (which are the topics I've seen through my research, which don't help me). I just want to do maths with one specific array.

You are not adding one to 7, you are adding one to an array that has a single index.
var myArrayIncreased = myArraySliced + 1;
//var myArrayIncreased = [7] + 1;
If you want to do the addition, you need to use the first index
var myArrayIncreased = myArraySliced[0] + 1;
//var myArrayIncreased = 7 + 1;

Instead of using slice, you could select it with it's array index
myArrayMapped[1] += 1;
which would make the final code
var myArray = ["7","7","0","0","32","17"];
console.log(myArray);
var myArrayMapped = myArray.map(Number);
console.log(myArrayMapped);
myArrayMapped[1] += 1;
console.log(myArrayMapped);

You are adding [7] with 1
instead of 7 with 1
[7]+1 = '71'
After get your numeric array sliced and get [7], you should refer to the element's content which should look:
var myArrayIncreased = myArraySliced.map(function(n){return n+1});
console.log(myArrayIncreased);

Do:
var myArrayIncreased = 1*myArraySliced + 1;

Related

How to randomly select numbers within an arbitrary range and add together using JavaScript arrays

I am trying to write some JavaScript that will select some random numbers from an array and then add those selected numbers to make a single total value.
For example if i had var array = [1, 22, 5, 88, 3, 105, 7, 88, 987] i would then like the code to select however many numbers it wants at random(amount selected changes every time it runs) and then add them together but i am not sure if this is even possible.
I am new to JavaScript so i have only managed to write code that adds all the array elements together instead of selecting at random.
var arr = [1,2,3,4,5,6];
var total=0;
for(var i in arr) { total += arr[i]; }
My code is very basic so please excuse me for this i'm still learning. Thank You
You could use the Math.rand() function in order to create a random index. In terms of code:
// The array with your elements
var arr = [1,2,3,4,5,6];
// An array that will keep track of the elements we have selected.
var selectedIndex = [];
// The sum.
var sum=0;
// times is the number of elements we want to select from arr and sum them.
for(var i=0; i<times; i++)
{
// Get a random integer number in the range [0, arr.length]
var index = Math.floor(Math.rand()*arr.length);
// check if the index we created has been selected again.
if(selectedIndex.indexOf(index)>-1)
{
// The created index has been selected again. So we must select another one,
// in order we get an item from the array only once.
while(selectedIndex.indexOf(index)>-1)
index = Math.floor(Math.rand()*arr.length);
}
// We push the created index in the selected index array.
selectedIndex.push(index);
// We increase the sum.
sum+=arr[index];
}
update
In order the above to be executed the caller should provide a value for the variable called times. This value in order to be valid shouldn't exceed the length of the array called arr.
Another way more elegant, it would be to follow on this part the solution that deitch suggested in his post.
var times = Math.floor((Math.random() * arr.length)+1)
The above should be placed just before the for statement.
I think you are looking something like:
<code>
function randormTotal() {
var arr = [1,2,3,4,5,6];
var total=0;
var noOfData = 3;
for(var i =0; i<noOfData; i++) {
var pos = Math.floor(Math.random()*(arr.length-1)) + 1;
total += arr[pos];
}
alert(total);
}
</code>
FYI, this method actually modifies the array, so you might want to copy it.
// randomly select how many elements you will pick
var i, total = 0, elmsCount = Math.floor((Math.random() * arr.length)+1), current;
// select that many elements
for (i=0; i<elmsCount; i++) {
current = Math.floor(Math.random()*arr.length);
total += arr.splice(current,1)[0];
}
// total is now the sum

How make jquery loop over with number

I am trying to assign a number to my variable i.e. colorswap1, colorswap 2, colorswap 3
I have the following
var i = 1-36;
// Get current image src
var curSrc = $('#colorswap'[i]).attr('src');
It doesn't seem to be putting the desired: colorswap1, colorswap2
Your variable declaration is doing the algebraic subtraction and will result in -35. You need a loop of some sort. Then, you concatenate the index with the string using the + operator. Because one of the things is a string, it will concatenate instead of "add".
Below is an example of what you can do:
for (var i = 1; i <= 36; i++) {
var curSrc = $('#colorswap' + i).attr('src');
// now do stuff with curSrc here
}

How to add dynamically growing array into another dynamic array

In my project i have arrays for date1, date2 and so on upto one month dates as shown below
var day1= [4,5,6,11];
var day2= [7,8,9,12];
var day3= [10,11,12,14];...
var day30= [1,2, 3, 4];
In the above each array exact size we dont know that may increase or decrease and i need to pass these values to the one more set of arrays like
var data1= [day1[0], day2[0], day3[0]];
var data2= [day1[1], day2[1], day3[1]];
var data3= [day1[2], day2[2], day3[2]];...
var data30= [day1[30], day2[30], day3[30]];
As per the day array size data array size will increase.
How to solve this issue any help..?
Consider using an object instead of variables:
var days = {
day1: [4,5,6,11],
day2: [7,8,9,12],
...
day30: [1,2, 3, 4]
};
Then you can do something like:
var data30 = [];
var i = 0;
while ( days.hasOwnProperty('day' + ++i) ){
data30.push(days['day' + i]);
}
Though given the sample data, data30 won't have any members because the first array has no member at index 30.
Check out JavaScript's push method.
http://www.w3schools.com/jsref/jsref_push.asp

Split function going Abnormal in JavaScript

This is the Contents of file from where i am reading...
aaa 3333,bbb 5,ccc 10
I am getting un defined for the keyvalue[2], [3], [4] and [5]. Why is it so???
I am actually first spliting based on , and then based on space.
because you split by comma first, so item is now 'PrimeSuiteId 3333'. When you split that by space you get two items only, so 3rd value (keyvalue[2]) and above is empty.
Edit: possible fix to make second part of your script work
swap
var items = contents.toString().split(',');
with
var items = contents.toString().replace(/,/,' ');
which will simply replace commas with spaces in the original string so your array of expected values matches up
Another edit: because splitting by comma or space is better (as in comments)
var contents = f.read();
Ti.API.info(contents);
var items = contents.toString(); // changed to return complete string not split
// removed for loop altogether
var keyvalue = items.split(/,|\s/); // changed to split by comma or space
var AppointmentSearchDaysAfter = keyvalue[0];
var AppointmentSearchDaysAfterValue = keyvalue[1];
var AppointmentSearchDaysBefore = keyvalue[2];
var AppointmentSearchDaysBeforeValue = keyvalue[3];
var PrimeSuiteId = keyvalue[4];
var PrimeSuiteIdValue = keyvalue[5];
From the contents in the contents file you should only be able to get values for
var AppointmentSearchDaysAfter = keyvalue[0];
var AppointmentSearchDaysAfterValue = keyvalue[1];
You only have one space for each data entry between the commas
Split function is working fine, you are expecting it to behave abnormal.
You will get only two values in array after split by space. From where will it bring 6 values!!!?
The rest values you will get in next iterations.
Instead of declaring individual variables for each item and then loading them from the contents string, you can reduce the whole thing to an object with key/value pairs:
var items = contents.split(',').reduce(function (acc, val) {
var split = val.split(' ');
return acc[split[0]] = split[1], acc;
}, {});
To test what the values are, try:
console.log(items.PrimeSuiteId); // outputs 3333
console.log(items.AppointmentSearchDaysBefore); // outputs 5
console.log(items.AppointmentSearchDaysAfter); // outputs 10

Remove items from based of substring in array jquery

This might seems a very newbie sort of question, but I am struggling with this as of now and seek some help.
Here is a example array in JavaScript
var SelectedFilters = ["[size:12:12]","[size:12:12]","[size:13:13]","[size:14:14]", "[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];
Now I wish to remove certain items from this array based on a search term, now the search term contains only a part of string such as
var searchTerm1 = 'size'
var searchTerm2 = 'color'
I have already tried the following code, but its not working:
var i = SelectedFilters.indexOf(searchTerm1);
if (i != -1)
{
SelectedFilters.splice(i, 1);
}
I have also tried running to through for loop, to iterate on all items, but again search failed as its not able to match 'size' OR 'color'
What I am looking: if searchterm1 is used, the resulted output will be like:
["[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];
and in case of searchterm2 is used the resulted output should be:
["[size:12:12]","[size:12:12]","[size:13:13]","[size:14:14]","[type:14:14]","[type:14:14]"];
It would be great if anyone can solve this puzzle, I am also trying to find a solution in the meantime.
Your attempt didn't work because .indexOf() on an Array looks for an exact match.
Since according to your question and comment you need to mutate the original Array, you should loop over the array and test each string individually and then call .splice() every time you find one that needs to be removed.
var SelectedFilters = ["[size:12:12]","[size:12:12]","[size:13:13]","[size:14:14]", "[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];
var searchTerm1 = 'size'
var searchTerm2 = 'color'
for (var i = SelectedFilters.length-1; i > -1; i--) {
if (SelectedFilters[i].startsWith(searchTerm1, 1)) {
SelectedFilters.splice(i, 1)
}
}
document.querySelector("pre").textContent =
JSON.stringify(SelectedFilters, null, 2)
<pre></pre>
The loop used above goes in reverse. This is important since every time we do a .splice(), the array gets reindexed, so if we went forward, we would end up skipping over adjacent items to be removed.
The .startsWith() method checks if the string starts with the given search term. I passed the second parameter a value of 1 so that it starts searching on the second character.
You can use filter method of array
var searchTerm = "size";
SelectedFilters = SelectedFilters.filter(function(val){
return val.indexOf( searchTerm ) == -1;
});
You can do it with Array#filter,
var searchTerm1 = 'size';
var result = SelectedFilters.filter(v => !v.includes(searchTerm1));
console.log(result); //["[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];
If you want to alter the original array then do,
var SelectedFilters = ["[size:12:12]", "[size:12:12]", "[size:13:13]", "[size:14:14]", "[color:14:14]", "[color:14:14]", "[type:14:14]", "[type:14:14]"];
var searchTerm1 = 'size',cnt = 0, len = SelectedFilters.length - 1;
while (cnt <= len) {
if (SelectedFilters[len - cnt].includes(searchTerm1)) SelectedFilters.splice(len - cnt, 1);
cnt++;
}
console.log(SelectedFilters);
DEMO

Categories

Resources