I am trying to get my array reversed without using the reverse() method. What am I doing wrong here?
This is the code that I have for now. I think I'm close but I'm stuck.
var zin = ["Kan jij achterstevoren praten?"];
var woorden = zin.split(" ");
woordenOmgedraaid = achterstevoren(woorden);
document.write(woordenOmgedraaid);
function achterstevoren(omgedraaid) {
var length = omgedraaid.length;
var woordenOmgedraaid = [];
var counter = 0;
for (var i = omgedraaid.length - 1; i >= 0; i -= 1) {
woordenOmgedraaid[counter] = omgedraaid[i];
counter += 1;
}
return woordenOmgedraaid;
}
Take the brackets off the "zin" variable.
var zin = "Kan jij achterstevoren praten?";
var woorden = zin.split(" ");
woordenOmgedraaid = achterstevoren(woorden);
console.log(woordenOmgedraaid);
function achterstevoren(omgedraaid) {
var length = omgedraaid.length;
var woordenOmgedraaid = [];
var counter = 0;
for (var i = omgedraaid.length - 1; i >= 0; i -= 1) {
woordenOmgedraaid[counter] = omgedraaid[i];
counter += 1;
}
return woordenOmgedraaid;
}
If you're trying to create a for loop that goes backwards through an array, you can simply write it as:
var arr = [1,2,3,4,5]
var reversedArr = []
for (var i = arr.length-1; i >= 0; i--) {
reversedArr.push(arr[i])
}
console.log(reversedArr)
Related
I want to match time and date
and result should be sum of time for each date...
for example...06/27 - should be sum of 30 and 90...so on.
How can I do that...
var array_date=["2017/06/27","2017/06/26","2017/06/27","2017/06/26","2017/06/28"]
var array_time=["30","50","90","120","20"]
var obj = array_date;
for (var i = 0 in obj) {
console.log("rr:"+obj[i]);
}
//To filter date I used below method...anyway.
var cleanArray = displayed_date.filter((value,index,self)=>{ return (self.indexOf(value) === index )});
First, since you're doing addition, best to convert your strings to numbers:
array_time = array_time.map(t=> +t);
Next, group and sum the times by date:
let data = array_date.reduce((acc, d, i)=> {
if(acc.hasOwnProperty(d)) acc[d] += array_time[i];
else acc[d] = array_time[i];
return acc;
}, {});
jsfiddle
You can do it just like this:
<script>
array_date=["2017/06/27","2017/06/26","2017/06/27","2017/06/26","2017/06/28"];
array_time=["30","50","90","120","20"];
var oData = [];
for(var i = 0; i < array_date.length; i++ ){
if(Object.keys(oData).length > 0){
var icount = 0;
for(var x = 0; x < Object.keys(oData).length; x++){
if(oData[x]['date'] == array_date[i]){
oData[x]['sum'] = parseInt(oData[x]['sum']) + parseInt(array_time[i]);
icount++;
}
}
if(icount == 0){
var oCreate = {"date":array_date[i], "sum":parseInt(array_time[i])}
oData.push(oCreate);
}
}else{
var oCreate = {"date":array_date[i], "sum":parseInt(array_time[i])}
oData.push(oCreate);
}
}
console.log(JSON.stringify(oData)); //oData is the final variable answer here.
</script>
Hope it will help.
The code below only executes through the first for loop once, yet all the other for loops perform as expected. Does anyone know why this is the case? I'm not sure how relevant the bulk of the (inefficient, poorly formatted) code within the loop is but I include it nonetheless.
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
for (i = 0; i < numbers.length; i++) {
var current = numbers[i];
var currentStr = current.toString();
var reverseStr = currentStr.split('').reverse().join('');
var reverseArr = [];
for (i = 0; i < reverseStr.length; i++) {
reverseArr.push(reverseStr[i]);
}
var A = 0;
for (i = 0; i < reverseArr.length; i += 2) {
A += Math.round((reverseArr[i]));
}
var evenDigits = [];
for (i = 1; i < reverseArr.length; i += 2) {
evenDigits.push(reverseArr[i]);
}
for (i = 0; i < evenDigits.length; i++) {
evenDigits[i] = evenDigits[i] * 2;
if (evenDigits[i] > 9) {
var temp = evenDigits[i].toString();
var firstInt = Math.round(temp[0]);
var secondInt = Math.round(temp[1]);
evenDigits[i] = firstInt + secondInt;
}
}
var B = 0;
for (i = 0; i < evenDigits.length; i++) {
B += evenDigits[i];
}
var sum = A + B;
if (sum % 10 == 0) {
console.log('Yes');
} else console.log('No');
}
In your code you are using same instance of 'i' variable to iterate all loops.
Solution is to use different index variables to iterate external and internal loops
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
var i = 0;
var j = 0;
for (j=0; j < numbers.length; j++) {
var current = numbers[j];
/...
}
JavaScript behaves like this because 'i' is not scoped to block (like in Java od C#). In ES2015 you can use let or const to bind variable to block scope (in this sample to for loop)
How can I split the below string into a 2dimensional-array:
Customer::Europe|UK|Scotland|Product::Drinks|Water|
array:
[Customer][Europe]
[Customer][UK]
[Customer][Scotland]
[Product][Drinks]
[Product][Water]
Not sure how to create the array. Haven't coded in years, so be kind
hArray= [];
vArray= [];
var i = j = 0;
var count = hierarchy.search(/[:|]+/);
write(hierarchy);
while (count > 0) {
if (hierarchy.indexOf(":") < hierarchy.indexOf("|") || (hierarchy.indexOf(":") > 0 && hierarchy.indexOf("|") == -1) ) {
hArray[j] = hierarchy.substr(0,hierarchy.indexOf(":"));
hierarchy = hierarchy.slice(hierarchy.indexOf(":")+2);
count = hierarchy.search(/[:|]+/);
j++;
} else
if (hierarchy.indexOf("|") < hierarchy.indexOf(":") {
vArray[i] = hierarchy.substr(0,count);
hierarchy = hierarchy.slice(count+1);
count = hierarchy.search(/[:|]+/);
i++;
}
if (count == -1) break;
//create multiArray ?
}
var source = "Customer::Europe|UK|Scotland|Product::Drinks|Water|";
var parts = source.split(/(\w+::)/);
var result = [];
for (var i = 1; i < parts.length; i += 2) {
var key = parts[i].replace("::", "");
var values = parts[i + 1].split("|");
for (var j = 0; j < values.length - 1; ++j) {
var line = new Array(2);
line[0] = key;
line[1] = values[j];
result.push(line);
}
}
console.log(result);
You can use Array.reduce like this. First, we split on | that is behind any owrd followed by ::. Then we reduce it, by using an array as memo and push an array into the memo, which we finally return.
var arr = input.split(/\|(?=\w+::)/).reduce(function(arr, str){
var array = str.split('::');
return arr.push(str.split('::')[1].split('|').filter(String).map(function(s){
return [array[0], s]
})), arr;
}, []);
I'm trying to write a function that will find which collection of numbers in the array adds up to the largest sum, and puts that number into the new array:
var num = ['267453', '345678', '876787'];
var newArray = [];
I'm actually at a loss here and not sure how to get started on this problem. Can someone help get me off on the right foot?
var num = ['267453', '345678', '876787'];
var sums =[];
num.forEach(function (el) {
string = el.split(''); //split into individual characters
var sum = 0; //have a storage ready
for (var i = 0; i < string.length; i++) { //iterate through
sum += parseInt(string[i],10); //convert from string to int
}
sums.push( sum);
}
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
alert("Max value is: "+sums.max());
Iterate over the strings, split the in to digits sum the digits
var arrayLength = num.length;
var sums = []
for (var i = 0; i < arrayLength; i++) {
var digitsAsChar = num[i].split("");
var tmpSum=0;
var digitsLength = digitsAsChar.length;
for(var y=0; y<digitsLength;y++){
tmpSum = tmpSum+parseInt(digitsAsChar[y]);
}
sums.push(tmpSum)
}
finaly sort the array:
sums.sort():
If I understood your question correctly, you can achieve this rather easily.
var num = ['267453', '345678', '876787'];
var max = -Infinity;
var maxi = 0;
num.forEach(function (el, i) {
var n = el.split('').reduce(function (a, b) {
return parseInt(a,10) + parseInt(b,10);
});
if (n > max) {
max = n;
maxi = i;
}
})
console.log(max); //43
console.log(num[maxi]); //"876787"
Regarding performance, this calls parseInt a number of times more than strictly necessary, if speed is a problem you may want to consider parsing first and summing separately.
Here is the fiddle for this :
var num = ['267453', '345678', '876787'];
var newArray = [];
var html = '';
for(var n=0; n<num.length; n++) {
var len = num[n].length;
count = 0;
for(var i=0; i<len; i++) {
count += parseInt(num[n].substring(i,i+1));
//console.log(count);
}
var temp1 = parseInt(num[n]);
newArray.push(count);
}
newArray = newArray.sort();
newArray = newArray.reverse();
var max = newArray[0];
https://jsfiddle.net/o6mryk1q/1/
Kind of a noob question, but I have a page with 42 checkboxes all placed into an array, but I need to split the array into 3 smaller arrays.
array(0) = smallOne(0);
array(1) = smallTwo(0);
array(2) = smallThree(0)
array(3) = smallOne(1);
array(4) = smallTwo(1);
array(5) = smallThree(1);
And so forth. Is there a method that does this or will I just need to list them all out?
Here's the javascript so far:
function SendForm() {
var elLength = form1.elements.length;
var chk = new Array(42);
var desc = new Array(14);
var local = new Array(14);
var other = new Array(14);
for (i = 0; i < elLength; i++) {
var count = 0;
var type = form1.elements[i].type;
if (type == "checkbox") {
if (form1.elements[i].checked) {
chk(count) = true;
}
else {
chk(count) = false;
}
count++;
}
else {
}
}
}
You could do something like this to assign them:
for (var i = 0; i < 14; i++)
{
var x = i * 3;
desc[i] = chk[x];
local[i] = chk[x + 1];
other[i] = chk[x + 2];
}