How to get next element in for loop in javascript - javascript

In a dataset I have different locators. Some places are free (locator = null). I would like to capture these and push them into arrays.
In the subarray may only be locations that are in a row. If a distance is greater than 1 then it comes to the next array.
const freeLocs = locs.filter(elem => !elem.locator)
let temp = []
let array2D = []
for(let i = 0; i < freeLocs.length-1; i++) {
let abs = Math.abs(freeLocs[i+1].position - freeLocs[i].position)
temp.push(freeLocs[i])
if(abs > 1) {
array2D.push(temp)
temp = []
}
}
console.log(array2D)
Now I have the problem that the last array is not filled.
https://jsfiddle.net/5yk0mpt9/2/

Problem starts here:
for(let i = 0; i < freeLocs.length-1; i++) {
with this condition you lose the last item of the array:
i < freeLocs.length-1
it needs to change like this:
i < freeLocs.length
but it also needs an extra check inside the loop before trying to get the
freeLocs[i + 1].position
for the last iteration
for example:
for (let i = 0; i < freeLocs.length; i++) {
temp.push(freeLocs[i]);
if (
(i === freeLocs.length - 1) ||
(Math.abs(freeLocs[i + 1].position - freeLocs[i].position) > 1)
) {
array2D.push(temp)
temp = [];
}
}
working demo here: DEMO

Related

Why do arrays within an array, which are the same, not show as the same? [duplicate]

This question already has answers here:
Why doesn't equality check work with arrays [duplicate]
(6 answers)
Why are two identical objects not equal to each other?
(9 answers)
Closed 4 months ago.
I'm sorry in advance that this code is super messy and inefficient, I am just learning, however I am concerned with one particular problem which I have outlined at the bottom.
The aim of this function is to return every unique array with no repetition of elements, from when every element of ArrTwo is put on the end of each element from arrOne.
function multOrdProduct(arrOne,arrTwo){
let backSet = [];
let finalSet = [];
let count = 0;
let tempArr = new Array(arrOne.length);
let permArrOne = [];
let permArrTwo = [];
let pushed;
let setPart = [];
let tempBackSort = [];
for(i=0; i < arrOne.length; i++){
permArrOne.push(arrOne[i]);
}
for(i = 0; i < arrOne.length;i++){
for(j = 0; j < arrTwo.length; j++){
setPart = permArrOne[i].map( x => x);
setPart.push(arrTwo[j]);
backSet.push(setPart);
}
}
// This makes backSet into the array which has every combination of the two arrays when all elements from arrTwo are put onto each element of arrOne
console.log(backSet);
count = 0;
for(z= 0; z < backSet.length - 1; z++){
backSet[count].sort();
tempBackSort = [];
for(k = 0;k < backSet[count].length - 1; k++){
if(tempBackSort.includes(backSet[count][k])){
backSet = backSet.filter(arr => (new Set(arr)).size == arr.length);
kon = 0;
break;
} else{
tempBackSort.push(backSet[count][k]);
kon = 1
}
}
if(kon===1){
count++;
}
backSet[count].sort();
}
// ^^ This filters out every array within backSet which has multiple of the same element
console.log(backSet);
let twoTempArr = backSet;
console.log(backSet[0] === backSet[2]);
return twoTempArr;
}
unArray = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
duArray = [1,2,3,4]
console.log(multOrdProduct(unArray,duArray));
function multOrdProduct(arrOne,arrTwo){
let backSet = [];
let finalSet = [];
let count = 0;
let tempArr = new Array(arrOne.length);
let permArrOne = [];
let permArrTwo = [];
let pushed;
let setPart = [];
let tempBackSort = [];
for(i=0; i < arrOne.length; i++){
permArrOne.push(arrOne[i]);
}
for(i = 0; i < arrOne.length;i++){
for(j = 0; j < arrTwo.length; j++){
setPart = permArrOne[i].map( x => x);
setPart.push(arrTwo[j]);
backSet.push(setPart);
}
}
// This makes backSet into the array which has every combination of the two arrays when all elements from arrTwo are put onto each element of arrOne
console.log(backSet);
count = 0;
for(z= 0; z < backSet.length - 1; z++){
backSet[count].sort();
tempBackSort = [];
for(k = 0;k < backSet[count].length - 1; k++){
if(tempBackSort.includes(backSet[count][k])){
backSet = backSet.filter(arr => (new Set(arr)).size == arr.length);
kon = 0;
break;
} else{
tempBackSort.push(backSet[count][k]);
kon = 1
}
}
if(kon===1){
count++;
}
backSet[count].sort();
}
// ^^ This filters out every array within backSet which has multiple of the same element
console.log(backSet);
let twoTempArr = backSet;
console.log(backSet[0] === backSet[2]);
return twoTempArr;
}
unArray = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
duArray = [1,2,3,4]
console.log(multOrdProduct(unArray,duArray));
The problem which I am having is that console.log(backSet[0] === backSet[2]); does not show true, even though when backSet is printed you can see that the first and third elements are the same. Are arrays within an array not equal if they have been sorted?

Why is this comparison not working, using google aps scripts?

The code below is not giving me the expected result.
It's to compare rows from two ranges and, although the second range's last row equals the one from the first range, it gives me false as the result.
var entryValuesCom = sheet.getRange(7, 1, LastRowSource, 9).getValues();
var dbDataCom = dbSheet.getRange(2, 1, dbSheet.getLastRow(), 9).getValues();
var entryVlArray = new Array();
var dbArray = new Array();
for (var r = 0; r < entryValuesCom.length; r++) {
if (entryValuesCom[r][0] != '' && entryValuesCom[r][5] != 'Daily Ledger Bal') {
entryVlArray.push(entryValuesCom[r]);
}
}
for (var a = 0; a < dbDataCom.length; a++) {
if (dbDataCom[a][1] != '' && dbDataCom[a][8] == bank) {
dbArray.push(dbDataCom[a]);
}
}
var duplicate = false;
loop1:
for (var x = 0; x < entryVlArray.length; x++) {
loop2:
for (var j = 0; j < dbArray.length; j++) {
if (JSON.stringify(entryVlArray) == JSON.stringify(dbArray)) {
duplicate = true;
break loop1;
}
}
}
Here's a snapshot of how the array is coming:
I've tried it using .join(), but still...
This is for thousands of rows, so is this going to do well performance wise?
I believe your goal as follows.
You want to compare the arrays of entryVlArray and dbArray using Google Apps Script.
When the duplicated rows are existing between entryVlArray and dbArray, you want to output duplicate = true.
Modification points:
When your script is modified, at if (JSON.stringify(entryVlArray) == JSON.stringify(dbArray)) {, all 2 dimensional arrays are compared. I think that this might be the reason of your issue. From your script, I think that it is required to compare each element in the 2 dimensional array.
When above points are reflected to your script, it becomes as follows.
Modified script:
From:
var duplicate = false;
loop1:
for (var x = 0; x < entryVlArray.length; x++) {
loop2:
for (var j = 0; j < dbArray.length; j++) {
if (JSON.stringify(entryVlArray) == JSON.stringify(dbArray)) {
duplicate = true;
break loop1;
}
}
}
To:
var duplicate = false;
for (var x = 0; x < entryVlArray.length; x++) {
for (var j = 0; j < dbArray.length; j++) {
if (JSON.stringify(entryVlArray[x]) == JSON.stringify(dbArray[j])) {
duplicate = true;
break;
}
}
}
console.log(duplicate)
By this modification, when each element (1 dimensional array) in the 2 dimensional array is the same, duplicate becomes true.
Note:
As other method, when an object for searching each row value is prepared, I think that the process cost might be able to be reduced a little. In this case, the script is as follows. Please modify as follows.
From:
var duplicate = false;
loop1:
for (var x = 0; x < entryVlArray.length; x++) {
loop2:
for (var j = 0; j < dbArray.length; j++) {
if (JSON.stringify(entryVlArray) == JSON.stringify(dbArray)) {
duplicate = true;
break loop1;
}
}
}
To:
var obj = entryVlArray.reduce((o, e) => Object.assign(o, {[JSON.stringify(e)]: true}), {});
var duplicate = dbArray.some(e => obj[JSON.stringify(e)]);
References:
reduce()
some()
Added:
About your following 2nd question,
AMAZING!!!! Would there be a way of capturing these duplicates in a pop up, using reduce() and some()?
When you want to retrieve the duplicated rows, how about the following script? In this case, I thought that filter() is useful instead of some().
Modified script:
var obj = entryVlArray.reduce((o, e) => Object.assign(o, {[JSON.stringify(e)]: true}), {});
// var duplicate = dbArray.some(e => obj[JSON.stringify(e)]);
var duplicatedRows = dbArray.filter(e => obj[JSON.stringify(e)]);
console.log(duplicatedRows)
In this modified script, you can see the duplicated rows at the log.
About a pop up you expected, if you want to open a dialog including the duplicated rows, how about adding the following script after the line of var duplicatedRows = dbArray.filter(e => obj[JSON.stringify(e)]);?
Browser.msgBox(JSON.stringify(duplicatedRows));

unable to loop the object in Angular

I have a data like below
data = ["I253,J665,l2575"]
and I need the the results like
I253,
J665,
l2575
when i tried to use for in i am getting like I253,J665,l2575 and I tried for loops also but not getting the result
let data = ["I253,J665,l2575"]
for (let i = 0; i > this.data.length; i++) {
console.log(i)
}
for (let x of this.data) {
console.log(x)
}
tried converting the data in to string and then using split changed into array but then also i am getting typeof object only
below is my stack blitz url =: https://stackblitz.com/edit/angular-ivy-drf1dk?file=src/app/app.component.ts
Modify your data variable like below:
data = ["I253", "J665", "l2575"];
for(let i = 0; i < this.data.length; i++){
console.log(this.data[i]);
}
If you have data variable as data = ["I253,J665,l2575"];
Then split it first and then loop through the generated array:
const arr = data[0].split(',');
for(let i = 0; i < arr.length; i++){
console.log(arr[i] + ',');
}
You were having multiple mistakes. First one was with for condition it should be i < this.data.length not i > this.data.length. Then you need to split and loop over it with for (let j = 0; j < data[i].split(',').length; j++) so data[i].split(',')[j] will return expected value.
In case of 2nd for...of loop you were simply logging whole value. Here also you need to split inside for...of and use one more loop to log.
Alternatively you can also use flatMap and loop over it like for (let m of data.flatMap(x => x.split(','))).
Try it below. You can use this.data, but it won't work in below example so it is used as simply data.
let data = ["I253,J665,l2575"];
console.log("Using for loop");
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].split(',').length; j++) {
console.log(data[i].split(',')[j]);
}
}
console.log("Using for...of loop");
for (let x of data) {
for (let y of x.split(',')) {
console.log(y);
}
}
console.log("Using flatMap");
for (let m of data.flatMap(x => x.split(','))) {
console.log(m);
}
Two ways to solve this.
Also note that your loop is wrong SHOULD NOT BE '>' and Should Be '<'
1. Your data is at array index zero so if you are to keep the data as is
let data = ["I253,J665,l2575"]
let splits = data[0].split(',')
for (let i = 0; i < splits.length; i++) {
console.log(splits[i])
}
or
let data = ["I253,J665,l2575"]
let splits = data[0].split(',')
for (let element of splits) {
console.log(element )
}
2. Fix the data string
let dataString = "I253,J665,l2575"
let splits = dataString.split(',')
for (let i = 0; i < splits.length; i++) {
console.log(splits[i])
}
or
let dataString = "I253,J665,l2575"
let splits = dataString.split(',')
for (let element of splits) {
console.log(i)
}
Clone of the example provided in question
https://stackblitz.com/edit/angular-ivy-izj7up

How to programmatically create 3D array that increments to a defined number, resets to zero, and increments again?

Starting with this initial 2D array:
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
I need to create this 3D array programmatically:
var fullArray = [
[[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]],
[[3,4],[0,1],[5,6],[2,3],[6,7],[3,4]],
[[4,5],[1,2],[6,7],[3,4],[0,1],[4,5]],
[[5,6],[2,3],[0,1],[4,5],[1,2],[5,6]],
[[6,7],[3,4],[1,2],[5,6],[2,3],[6,7]],
[[0,1],[4,5],[2,3],[6,7],[3,4],[0,1]],
[[1,2],[5,6],[3,4],[0,1],[4,5],[1,2]],
[[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]],
[[3,4],[0,1],[5,6],[2,3],[6,7],[3,4]],
[[4,5],[1,2],[6,7],[3,4],[0,1],[4,5]],
[[5,6],[2,3],[0,1],[4,5],[1,2],[5,6]]
];
See the pattern?
On each pair, the [0] position should increment to 6 (from any starting number <= 6) and then reset to 0 and then continue incrementing. Similarly, the [1] position should increment to 7 (from any starting number <= 7) and then reset to 1 and then continue incrementing.
In this example, there are 10 2D arrays contained in the fullArray. However, I need this number to be a variable. Something like this:
var numberOf2DArraysInFullArray = 12;
Furthermore, the initial array should be flexible so that initialArray values can be rearranged like this (but with the same iteration follow-through rules stated above):
var initialArray = [[6,7],[2,3],[5,6],[4,5],[1,2],[6,7]];
Any thoughts on how to programmatically create this structure?
Stumped on how to gracefully pull this off.
Feedback greatly appreciated!
Here's a solution, I've separated the methods, and I made it so if instead of pairs it's an N size array and you want the [2] to increase up to 8 and reset to 2, if that's not needed you can simplify the of the loop for(var j = 0; j < innerArray.length; j++)
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
var create3DArray = function(array, size){
var newArray = [initialArray];
for(var i = 0; i < size; i++)
{
newArray.push(getNextArrayRow(newArray[i]));
}
return newArray;
}
var getNextArrayRow = function(array){
var nextRow = [];
for(var i = 0; i < array.length; i++)
{
var innerArray = array[i];
var nextElement = [];
for(var j = 0; j < innerArray.length; j++)
{
var value = (innerArray[j] + 1) % (7 + j);
value = value === 0 ? j : value;
nextElement.push(value);
}
nextRow.push(nextElement);
}
return nextRow;
}
console.log(create3DArray(initialArray,3));
Note, the results from running the snippet are a bit difficult to read...
var initialArray = [[2,3],[6,7],[4,5],[1,2],[5,6],[2,3]];
var numOfArrays = 10;
// get a range array [0, 1, 2, ...]
var range = [];
for (var i = 0; i < numOfArrays; i++) {
range.push(i);
}
var result = range.reduce(function(prev, index) {
if (index == 0) {
return prev;
}
prev.push(transformArray(prev[index - 1]));
return prev;
}, [initialArray])
console.log(result);
function transformArray(arr) {
return arr.map(transformSubArray)
}
function transformSubArray(arr) {
return arr.map(function(val) {
return val == 7 ? 0 : val + 1;
})
}
Here's a pretty simple functional-ish implementation

loop different arrays javascript

Hello there am trying to save news tweets into three different array which are dynamically created.
am finding trouble when i want to get the text from each one of those array and make another request to twitter.
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
news_array[i] = [{user:user,date:date,profile_img:profile_img,text:text,url:url}];
}
for (var i = 0; i < news_array.length; i++) {
for (var x=0; x<i.length; x++){
console.log(news_array[i][x].user);
}
}
});
}
It doesn't show anything on the console.log.
thanks for the help!!!!!
First, make sure that your count is smaller than the data array's length, otherwise this could lead to some undefined values:
for (var i = 0; i < count && i < data.length; i++) …
Then, why are you creating all those one-element-arrays in the news_array? Just use only objects.
This would solve your actual issue: You are looping wrong over those inner arrays. The correct code would be
for (var i = 0; i < news_array.length; i++) {
for (var x = 0; x < news_array[i].length; x++){
console.log(news_array[i][x].user);
}
}
Also, you should indent your code properly. You have some odd braces around, which don't make the code readable.
The problem is the x<i.length in the for loop near the end. i is a number, so it doesn't have a length. You probably meant x < news_array[i].length.
You may try the following:
Use the push method to append elements / data in your array new_array
Use only 1 loop for to display the user value on console
So your code will be something like this:
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
// Pushing your elements in your array, 1 by 1
news_array.push({user:user,date:date,profile_img:profile_img,text:text,url:url});
}
// Here you only need 1 loop!
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i][x].user);
}
});
}
First thing is i would loop the first one till data.length rather than count because its an api and it "might" or "might not" return all the data. So it will be fool proof to loop till data.length
And your problem is with i.length
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i].user);
}
this should work. not sure why you had to loop through a loop.

Categories

Resources