change array index in for loop before push in javascript - javascript

var array = [23,34,56,35]
I want to do this using a for loop in javascript
var array = [
2:23
3:34
4:56
5:35
]
instead of
var array = [
0:23
1:34
2:56
3:35
]

You can use forEach of array, to do:
var array = [23,34,56,35];
var result = [];
array.forEach((current,index)=>{
result[index+2] = current;
});
console.log(result);

Related

How to get the output value of for loop in an array in javascript

Hi i am getting the values from a dynamically created input form with following loop.
i need to store the for loop out put value to be stored in an array like below
points= [[0,420],[10,373],[20,340],[30,313],[40,293],[50,273],[60,259],[70,243]]
my for loop code
//for example intId = 4
for(i=0;i<intId;i++){
var it=i+1
var af = $('#af'+it).val()
var sp = $('#sp'+it).val()
var ad = [af,sp]
console.log(ad);
}
i need the result in this format as mentioned above
for eg.
[[af1,sp1],[af2,sp2],[af3,sp3],...]
Unless I'm missing something exceptionally obvious here, all you need to do is create an array, and then .push the new arrays into it...
var newArray = [];
for (i=0;i<intId;i++){
var it=i+1
var af = $('#af'+it).val()
var sp = $('#sp'+it).val()
var ad = [af,sp]
newArray.push(ad);
}
console.log(newArray);
As per the comment by the OP...
i need the output like this [2, 3] [1, 2] but i am getting like this ["2", "3"] ["1", "2"]
Then use parseInt to get the actual number...
var newArray = [];
for (i=0;i<intId;i++){
var it=i+1
var af = parseInt($('#af'+it).val())
var sp = parseInt($('#sp'+it).val())
var ad = [af,sp]
newArray.push(ad);
}
console.log(newArray);
You can create an array and store the values in the array.
const arr = [] // Initialize an empty array
for(i=0;i<intId;i++){
var it = i+1
var af = $('#af'+it).val()
var sp = $('#sp'+it).val()
var ad = [af,sp]
arr.push(ad); // Append to array
}
console.log(arr)

Checking multiple variables with the same "rules"

I have to construct an array of objects. I can do it "long hand," but I'm hoping to find a way to iterate through some variables and check each at "push" them into the right spot in the array.
I have this:
//this is the starting array...I'm going to update these objects
operationTime = [
{"isActive":false,"timeFrom":null,"timeTill":null},//Monday which is operationTime[0]
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null}
];
//I get the below via an API call
var monHours = placeHours.mon_open_close;
var tueHours = placeHours.tue_open_close;
var wedHours = placeHours.wed_open_close;
var thuHours = placeHours.thu_open_close;
var friHours = placeHours.fri_open_close;
var satHours = placeHours.sat_open_close;
var sunHours = placeHours.sun_open_close;
var sunHours = placeHours.sun_open_close;
//here's where I'm stuck.
if (monHours.length>0){
var arr = monHours[0].split("-");
operationTime[0].isActive= true;
operationTime[0].timeFrom= arr[0];
operationTime[0].timeTill= arr[1];
}
else {
operationTime[0].isActive= false;
}
My if/else works perfectly in the above example using Monday, but I don't want to write this for seven days of the week making it unnecessarily complicated. How could I condense this into a single "function" that'll test each variable and push it into the array object in the correct position?
I guess you can put the keys in an array, and then use forEach loop through operationTime and update the object based on the index:
operationTime = [
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null}
];
// make an array of keys that has the same order of the operationTime
var keys = ['mon_open_close', 'tue_open_close', 'wed_open_close', 'thu_open_close', 'fri_open_close', 'sat_open_close', 'sun_open_close'];
var placeHours = {'mon_open_close': ['08:00-17:00'], 'tue_open_close':[], 'wed_open_close':[], 'thu_open_close':[], 'fri_open_close':[], 'sat_open_close':[], 'sun_open_close':['10:20-15:30']}
operationTime.forEach( (obj, index) => {
var dayHours = placeHours[keys[index]];
if(dayHours.length > 0) {
var arr = dayHours[0].split("-");
obj.isActive= true;
obj.timeFrom= arr[0];
obj.timeTill= arr[1];
}
})
console.log(operationTime);
You can try this way with foreach all days's hour,
$all_hours = [monHours, tueHours , wedHours , thuHours , friHours , satHours ,sunHours];
foreach($all_hours as $k=>$hours){
if ($hours.length>0){
$arr = $hours[k].split("-");
operationTime[$k].isActive= true;
operationTime[$k].timeFrom= $arr[0];
operationTime[$k].timeTill= $arr[1];
}
else {
operationTime[$k].isActive = false;
}
}
You can use Object.entries() to iterate properties and values of an object as an array, .map() to define and include index of iteration in block of for..of or other loop. The index is utilized to reference object at index of operationTime array
for (let
[key, prop, index]
of
Object.entries(placeHours)
.map(([key, prop], index) => [key, prop, index]))) {
if (prop.length > 0 ) {
let [arr] = prop.split("-");
operationTime[index].isActive = true;
operationTime[index].timeFrom = arr[0];
operationTime[index].timeTill = arr[1];
}
}

merge unknown number of sub-arrays in array

I have an array like this:
arr = [ [[x,x],[x,x]], [[x,x],[x,x],[x,x]], [[x,x]] ]
and I want to turn it into an array like this:
arr = [ [x,x],[x,x] , [x,x],[x,x],[x,x], [x,x] ]
so I have tried this:
for (var i=1; i< arr.length; i++){ arr[0].concat(arr[i]); }
but it does not work. How can I 'merge' this intermediate level of array?
With ES6 you can use spread syntax with concat()
var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ]
var merged = [].concat(...arr)
console.log(JSON.stringify(merged))
For older versions of ecmascript the same can be done using concat() and apply().
var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ]
var merged = [].concat.apply([], arr)
console.log(JSON.stringify(merged))
The array.concat() doesn't change the array you call it on, but rather returns a new array - a new array you are ignoring.
You should create a result array and then append everything to that, instead of trying to modify arr.
var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ];
var new_arr = [];
for(var i = 0; i < arr.length; i++){
new_arr = new_arr.concat(arr[i]);
}

Why this array producer code doesn't work as it shows?

I have used some code as bellow to produce new array from tow arrays :
var arr1 = [['wo','ss'],['er','me'], ['lo','to']];
var arr2 = [['mine','yours'],['from', 'theme']];
var arr3 = [];
var temp = [];
//this will be an array of arrays that every index is arr2 + one index from arr1
var end = [];
arr1.forEach(function(item) {
temp = arr2;
temp.push(item);
end.push(temp);
})
console.log(end)
But after the result is not my desired and is not logical
[
['mine','yours'], ['from','theme'], ['wo', 'ss'],
['mine', 'yours], ['from','theme'], ['er', 'me'],
['mine', 'yours], ['from','theme'], ['lo', 'to']
]
You must clone the arr2 for each iteration defining temp as new array each time
var arr1 = [['wo','ss'],['er','me'], ['lo','to']];
var arr2 = [['mine','yours'],['from', 'theme']];
var arr3 = [];
var end = [] //this will be an array of arrays that every index is arr2 + one index from arr1
arr1.forEach(function(item) {
var temp = arr2.slice();
temp.push(item);
end.push(temp);
})
console.log(end);
This code works as you expected
In your code Array#push method will push values to arr2 which update the array(since temp is reference to array arr2) on each iteration.
Use Array#concat method which generates a new concatenated array although Array#map can be used for generating the array.
var arr1 = [
['wo', 'ss'],
['er', 'me'],
['lo', 'to']
];
var arr2 = [
['mine', 'yours'],
['from', 'theme']
];
var end = arr1.map(function(item) {
return arr2.concat([item]);
})
console.log(JSON.stringify(end))
UPDATE : Currently it creates the reference to the parent array updating one will change other. if you want a new array with the element then do it with Array#map and Array#slice methods .
var arr1 = [
['wo', 'ss'],
['er', 'me'],
['lo', 'to']
];
var arr2 = [
['mine', 'yours'],
['from', 'theme']
];
var end = arr1.map(function(item) {
return arr2.map(function(v) {
return v.slice();
}).concat([item.slice()]);
})
console.log(end)

Multidimensional Array splitting into objects javascript

I want to split my multidimensional array into objects.
I have made a array:
var arrayFirstLast = [
[58.94142647682763][23.5423357],
[59.94142647682765][24.5423357],
];
I know only how do deal with array like:
var arrayFirstLast=[58.94142647682763],[23.5423357];
and I want:
var arrayLongLat= [
{
"long":58.94142647682763,
"lat":23.5423357
},
{
"long":59.94142647682763,
"lat":24.5423357
}
];
for the output you want is an array of objects.
so for this
var arrayFirstLast=[[58.94142647682763,23.5423357],
[59.94142647682765,24.5423357]];
var arrayLongLat = [],
latLon = {};
for(var i in arrayFirstLast){
latLon = {long: arrayFirstLast[i][0], lat: arrayFirstLast[i][1]};
arrayLongLat.push(latLon);
}
You might want to look at your array, it is written in an incorrect syntax.
So let's take the array:
var arrayFirstLast =
[[58.94142647682763, 23.5423357], [59.94142647682765, 24.5423357]];
And then we loop through it and make objects out of it:
for (var i = 0; i < arrayFirstLast.length; i++) {
var obj = { "long": arrayFirstLast[i][0], "lat": arrayFirstLast[i][1] };
arrayLongLat.push(obj);
}
Iterate over array and set new array with objects:
var arrayFirstLast=[[58.94142647682763][23.5423357],
[59.94142647682765][24.5423357],
];
var newA = Array();
for ( var i = 0 ; i < arrayFirstLast.length ; i++ )
newA.push({"long":arrayFirstLast[i][0],"lat":arrayFirstLast[i][1]});
newA Array contains results.

Categories

Resources