looping over certain elements on an array in javascript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i have a very long array of points like so:
latlngs: [
[3.063895, 50.636767],
[3.06339, 50.637233],
[3.063309, 50.637278],
[3.063254, 50.637288],
[3.063103, 50.637267],
[3.061939, 50.636762],
[3.059679, 50.635821],
[3.056687, 50.634532],
[3.067972, 50.628265],
[3.068189, 50.628169],
[3.068389, 50.628159],
[3.06959, 50.628201],
[3.075613, 50.629068],
[3.077604, 50.629383],...
// 4500 array more
]
And i would like to loop on one on n element on it to make the computation less intensive. For example i would like to loop on 1 on 6 elements. What would be the best way to do that ?

A for loop seems like the simplest solution:
for (let n = startIndex; n < endIndex; ++n) {
const entry = theArray[n];
// ...
}
You can also create an array from a slice of an array, but it...creates an array (and, in this example, an iterator object, though that may get optimized away):
for (const entry of theArray.slice(startIndex, endIndex)) {
// ...
}
In a comment, user753642 said they think you mean "...elem 0, elem 6, elem 12". If so, you'd use n += 6 rather than ++n:
for (let n = startIndex; n < endIndex; n += 6) {
const entry = theArray[n];
// ...
}
That assumes you know endIndex is <= theArray.length. If you're accepting it from outside you may not know that, in which case:
for (let n = startIndex, end = Math.min(theArray.length, endIndex); n < end; n += 6) {
const entry = theArray[n];
// ...
}

A simple for loop is enough
for (let index = 0; index < latlngs.length; index+= 6) {
// do whatever computation you need with latlngs[index]
}

an alternative to the for loop with 6 increment can be the usage of modulo
latlngs.forEach((x, i) => {
// cbk + return in case of modulo !== 0 is negligible
// in regards to doyourstuff
if (i % 6 !== 0) { return }
doyourstuff
})

Related

i have to sum the numbers like sum of 55555 is 25 and sum 0f 25 is 7 ,but we have to use while loop specifically to solve it? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 17 days ago.
Improve this question
I have to sum the numbers like sum of 55555 is 25 and sum of 25 is 7, but we have to use while loop specifically to solve it
function createCheckDigit(membershipId) {
string = membershipId.split('');
let sum = 0;
for (var i = 0; i \< string.length; i++) {
sum += parseInt(string\[i\],10);
}
return sum \>= 10 ? createCheckDigit(String(sum)) : sum;
}
console.log(createCheckDigit("55555"));
Now i have to do this using while loop. The final answer of the code will be 7 if the number is 55555.
Here is a simple implementation (strings can be iterated like arrays)
function createCheckDigit(membershipId) {
membershipId = String(membershipId)
let sum = i = 0
while (i < membershipId.length) {
sum += Number(membershipId[i++])
}
return (sum >= 10) ? createCheckDigit(sum) : sum
}
console.log(createCheckDigit("55555"))
console.log(createCheckDigit(77777))
To find the digital root of a number, you need to repeatedly sum its digits until it reachs a single-digit number
function createCheckDigit(membershipId) {
let sum = membershipId;
while (sum >= 10) {
let digits = sum.toString().split('');
sum = 0;
for (let i = 0; i < digits.length; i++) {
sum += parseInt(digits[i]);
}
}
return sum;
}
console.log(createCheckDigit("55555"))

JavaScript: How to create a function that receives an array of numbers and returns an array containing only the positive numbers? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
What is Wrong with this Code? I should create a function that receives an array of numbers and returns an array containing only the positive numbers. How can it be modified? Especially Modified. Not another code!
all = prompt("Give me an array of numbers seperated by ','");
var splitted = all.split`,`.map(x=>+x);
function returner(splitted){
var positive = [];
for(var i = 0; i < splitted.length; i++);{
var el = splitted[i];
if (el >= 0){
positive.push(el);
}
}
return positive;
}
var positive = returner(splitted);
print(positive);
First I noticed that you are using print to check your output - that should be console.log().
But your real mistake is the semicolon after the for bracket in line 7.
Here is a working code-snippet:
let all = prompt("Give me an array of numbers seperated by ','");
let splitted = all.split`,`.map(x => +x);
function returner(splitted) {
let positive = [];
for (let i = 0; i < splitted.length; i++) {
const el = splitted[i];
if (el >= 0) {
positive.push(el);
}
}
return positive;
}
var positive = returner(splitted);
console.log(positive);
Just remove the semicolon after the for statement as:
all = prompt("Give me an array of numbers seperated by ','");
var splitted = all.split`,`.map(x=>+x);
function returner(splitted){
var positive = [];
for(var i = 0; i < splitted.length; i++){
var el = splitted[i];
if (el >= 0){
positive.push(el);
}
}
return positive;
}
var positive = returner(splitted);
console.log(positive);
practically with that semicolon you were doing "nothing" n times and then executing the block on it's own which didn't help filling your array since the i variable is already passed the last index of the array and so splitted[i] results to undefined which is not >=0 thus nothing gets pushed to the positive array.
(also I'd imagine you want a console.log at the end instead of print? )
Why don't you use filter?
var array = [3, -1, 0, 7, -71, 9, 10, -19];
const getpositiveNumbers = (array) => array.filter(value => value > 0);
var positives = getpositiveNumbers(array);
console.log(positives);
Anyway, as #trincot noticed, your code is wrong.

Get palindrome length from string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have one string as "testaabbaccc" in this string we contain palindrome as "abba" and it's length is 4 but how can we identify this with a JavaScript code.
var string ="testaabbaccc"
Need Output as abba is palindrome and length is 4
You can use this article and modify it to your needs.
Working demo
function isPalindrome(s) {
var rev = s.split("").reverse().join("");
return s == rev;
}
function longestPalind(s) {
var maxp_length = 0,
maxp = '';
for (var i = 0; i < s.length; i++) {
var subs = s.substr(i, s.length);
for (var j = subs.length; j >= 0; j--) {
var sub_subs = subs.substr(0, j);
if (sub_subs.length <= 1)
continue;
if (isPalindrome(sub_subs)) {
if (sub_subs.length > maxp_length) {
maxp_length = sub_subs.length;
maxp = sub_subs;
}
}
}
}
return maxp;
}
console.log(longestPalind("testaabbaccc"));
console.log(longestPalind("testaabbaccc").length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Explanation of two loops for Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Can someone explain how this solution works for an exercise that makes you find the most frequent element in an array, returning the number of times its been counted? I'm new to JS and just need a bit of help with understanding the logic!
function mostFrequentItemCount(array) {
var freq = 0;
var mostFreq = 0;
for (var i = 0; i <= array.length; i++) {
for (var j = i; j < array.length; j++) {
if (array[i] === array[j]) {
freq++;
}
if (freq >= mostFreq) {
mostFreq = freq;
}
if (array.length === 0) {
return 0;
}
}
freq = 0;
}
return mostFreq;
}
mostFrequentItemCount([4, 3, 4, 4, 5, 5, 5, 5, 4, 3])
Apart from the error mentioned on comments, the logic that it takes each element of the array in the first loop, and compares it to the other elements placed after (second loop starts at first loop current index), and counts the occurrences.
IMO there must be a more optimized way to do this, because elements are counted many times in situations where it is not relevant (no use to count the 4 again with omitting the first when we meet the second one)
It also doesn't cope with same frequence elements..
if you are really interested in a REAL JS solution:
var hashMap = {}; // in js any object can be also used as a map
var array = [4, 3, 4, 4, 5, 5, 5, 5, 4, 3];
for (var i = 0; i < array.length; i++) // there are better ways of doing this with js es6
{
if (!hashMap[array[i]]) hashMap[array[i]] = 0; // if this is the first time of this value in the map - initialize it with zero
hashMap[array[i]]++; // increase the count of each value
}
for (var value in hashMap)
{
console.log(value + ' ' + hashMap[value]); // print each value with the correct amount of instances
}
Nested loops should be avoided performance-wise, and I'm sure there is a better solution, but still I'd like to give you an understanding of how the provided snippet works:
function mostFrequentItemCount(array) {
// initialize variables
var freq = 0; // variable that will hold frequency count of the currently checked element
var mostFreq = 0; // variable that will hold the highest frequency count
// iterate over all elements of the array
for (var i = 0; i <= array.length; i++) {
// from the current index i, iterate over the array again,
// so all "following" elements will be checked
for (var j = i; j < array.length; j++) {
if (array[i] === array[j]) {
// if one of the following elements equals
// the current element of the first for loop,
// increase frequency count
freq++;
}
// if the frequency of this element is higher then the
// currently highest frequency, set the mostFreq variable
// to the frequency of the current element
if (freq >= mostFreq) {
mostFreq = freq;
}
// if the array has no elements, return 0
if (array.length === 0) {
return 0;
}
}
// reset freq to 0 so we can start fresh with the next element
freq = 0;
}
// return the most frequent:
return mostFreq;
}
Please also note that this only works for an array containing only numbers (and will return the frequency, not the most frequent number, as mentioned in the comments). Adaptions would have to be made to to return the actual element when strings or objects are to be compared.
And another solution:
function mostFrequentItemCount(array) {
return array.reduce(function(p,c){
if(p[c] === undefined)
p[c] = 0;
p[c]++;
if(p.mostFrequent == undefined || p[c]>p[p.mostFrequent])
p.mostFrequent = c;
return p;
},{}).mostFrequent;
}
This function does not find the most frequent element, only the amount of times the most frequent element showed up.
It works by counting the amount of times each element show up.
The outer for loop makes sure you check every element in the array. The inner loop counts how many times this element showed up. Every time the inner loop finds an element more frequent than the previous elements, it updates mostFreq.
Its worth noticing that this code can be optimized by using an auxiliar array, that counts how many times each element showed up. Also, as stated in comments, the loop conditions are incorrect, since array.length returns the first empty position in the array.

find missing element in a javascript object array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
how would one write a function to find the missing element of an numeric array for example:
getMissingElement( [0, 5, 1, 3, 2, 9, 7, 6, 4] ) // returns 8
Is there just one element missing, and the others are for sure non-repeating?
Then recall that the formula to compute the sum of 0 + 1 + ... + (N-1) is (N-1)*N/2, and the difference from this to the sum in your array is the missing element:
function getMissingElement(array) {
var sum = 0;
var N = array.length + 1;
for(i = 0; i < N-1; ++i) {
sum += array[i];
}
return (N-1)*N/2 - sum;
}
function getMissingElement(myArray) {
myArray.sort();
myAray.reverse()
for(var i = 1; i < myArray.length; i++) {
if(myArray[i] - myArray[i-1] != 1) {
//log your numbers or print them or whatever you like
}
}
}
This is assuming the most basic definition of "missing item", where the missing item is between existing values on either side.
Here's way to do it:
arr.sort(function(x, y){return x - y})
.map(function(x, i, me){return me[i+1]-x > 1 && x+1})
.filter(Number)
This will give you an array with missing numbers, for [0,2,4] it will give you [1,3]

Categories

Resources