Loop won't break in javascript - loops

So I am trying to create a function where it will display to me the FIRST even number divisible by 2. The values to be divided are inside an array and another function helps me determine whether the values in the array are divisible by 2. The problem is that the loop won't break and the loop continues until the last value of the array. I want it to break once it finds the first number divisible by 2. So in this case the loop should stop once it reaches value 8 in the array but it doesn't and continues until 10. I hope you can help me
This is my code:
function findElement(arr, func) {
var num = 0;
arr.sort();
for(var i = arr[0]; i <= arr[arr.length-1]; i++) {
if(func(arr[i])) {
num = arr[i];
break;
}
if(!func(arr[i])) {
num = undefined;
}
}
return num;
}
findElement([1, 3, 5, 8, 9, 10], function(num){ return num % 2 === 0; });

I believe your for over array is off.
Instead of
for(var i = arr[0]; i <= arr[arr.length-1]; i++) {
It should be
for(var i = 0; i <= arr.length-1; i++) {
Otherwise, you might as well be verifying undefined array indexes.

Please remove arr.sort() your function works find
please find the updated code .its working fine run and check.
function findElement(arr, func) {
var num = 0;
// arr.sort();
for(var i = arr[0]; i <= arr[arr.length-1]; i++) {
if(func(arr[i])) {
num = arr[i];
break;
}
if(!func(arr[i])) {
num = undefined;
}
}
return num;
}
console.log(findElement([1, 3, 5, 8, 9, 10], function(num){ return num % 2 === 0; }));

Related

Sort and print number of occurences of random numbers

const randomNum = [];
for (let i = 0; i <= 20; i += 1) {
randomNum.push(Math.floor(Math.random() * 20 + 1));
}
then
function getOccurrence(array, value) {
return array.filter((x) => x === value).length;
}
My goal is to print out something along the line of
Number 1, 6, 12, 3, 9 occurred 1 times.
Number 2, 5, 7, 19, 17 occurred 2 times.
Number 15, 11 occurred 3 times.
And so on.
Any idea how i should go about this?
I was thinking of making a function, something along the line of
function numberOccurrence(arr, arrLength){
}
So i in the future could feed it ANY array with with x amount of numbers in it, but I'm unsure how to go forward.
I've tried multiple .includes, .indexOf, ifs and so forth, but i feel stuck, could anyone give me a push in the right direction?
I feel like having a loop which counts how many times 1 occurs, then saves that into an object like this
numObj = {
1: 2,
2: 1,
3: 4,
}
Where the object is built as soon as the function runs, and it builds it based on the arrLength parameter i feed the function in the beginning.
Anything is appreciated, thank you!
Update:
I manage to SOMETIMES print part of the answer right with this:
function getOccurrence(array, value) {
return array.filter((x) => x === value).length;
}
for (let i = 1; i <= randomNum.length; i += 1) {
let numOccurr = [];
for (let j = 1; j <= randomNum.length; j += 1) {
if (randomNum.includes(j)) {
if (getOccurrence(randomNum, j) === i) {
numOccurr.push(j);
if (j === randomNum.length) {
printOut(`Number: ${numOccurr.join(', ')} occurrs ${i} times.`);
numOccurr = [];
}
}
}
}
}
if i check my array after "Number: 20 occurred 4 times" gets printed, i see that the answer is correct, problem is, sometimes it prints every number generated 1 time, then sometimes only those generated 2 times, and so on. And sometimes nothing gets printed
SOLVED:
This code worked for me
const randomNum = [];
for (let i = 0; i < 20; i += 1) {
randomNum.push(Math.floor(Math.random() * 20 + 1));
}
function getOccurrence(array, value) {
return array.filter((x) => x === value).length;
}
for (let i = 1; i <= randomNum.length; i += 1) {
const numOccurr = [];
for (let j = 1; j <= randomNum.length; j += 1) {
if (randomNum.includes(j)) {
if (getOccurrence(randomNum, j) === i) {
numOccurr.push(j);
}
}
}
if (numOccurr.length !== 0)
printOut(`Number: ${numOccurr.join(', ')} occurred ${i} times.`);
}

Comparing variable to Math.max(...arr) not returning accurate answer

I'm trying to complete an easy LeetCode question: https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ but cannot figure out why my code is not working correctly. Here is the question and a correct solution:
Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has.For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies.
Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Here is my current code:
var kidsWithCandies = function(candies, extraCandies) {
let newArr = [];
const max = Math.max(...candies)
for(i=0; i<candies.length; i++) {
let newVal = candies[i] + extraCandies
if (newVal >= max) {
newArr.push('true')
} else {
newArr.push('false')
}
}
return newArr
};
My code is returning [true,true,true,true,true] instead of [true,true,true,false,true].
I've used console.log() to check the values for 'max' and 'newVal' as the loop runs, and they are all correct, so there must be something wrong with my if statement, but I can't figure out what.
Thank you for your help!
You've answered your own question. Nonetheless, this'd also pass on LeetCode:
const kidsWithCandies = (candies, extraCandies) => {
let maxCandies = 0;
const greatest = [];
for (const candy of candies) {
(candy > maxCandies) && (maxCandies = candy);
}
for (let index = 0; index < candies.length; ++index) {
greatest.push(candies[index] + extraCandies >= maxCandies);
}
return greatest;
};

How can I push element in an array whenever a function get called?

I am implementing infinite scroll. I Have an array named hotels which gets data from $http.get() method. Now I want to populate a new array named hotelsNew[] with the value of hotels array. But I want to push value in the hotelsNew incrementing value of m and j.
The value of m and j need to be updated (increment) whenever function loadMore() is called. Initial value of m is 0 and j is 5. When loadMore() gets called, again m will be 5 and j will be 10 and so on.
I am unable to save value of m and j anywhere because $http.get() is asynchronous. Is there any proper way to save values of m and j, and reuse it when loadMore() gets called again?. Maximum j value is 40. and when m = j(40), it will stop.
Here is my controller code.
$scope.loadMore = function() {
$http.get(url).success(function(data, status, headers, config) {
if(data) {
$scope.hotels = data.hotels;
for(var i = m; i < j; i++) {
console.log('i=',i);
$scope.hotelsNew.push($scope.hotels[i]);
console.log('hotelsNew',$scope.hotelsNew);
}
}
}
How can i increment m and j value ?any idea?
If m and j increments same amount each time, you can create a local variable in your controller.
var m = 0, j = 5;
$scope.loadMore = function() {
$http.get(url).success(function(data, status, headers, config) {
if(data && j < 40) {
$scope.hotels = data.hotels;
for(var i = m; i < j; i++) {
console.log('i=',i);
$scope.hotelsNew.push($scope.hotels[i]);
console.log('hotelsNew',$scope.hotelsNew);
}
m += 5;
j += 5;
}
}
}
Use a promise to avoid async call
$scope.loadMore = function() {
$http.get(url).then(function(data) {
if(data) {
$scope.hotels = data.hotels;
for(var i = m; i < j; i++) {
console.log('i=',i);
$scope.hotelsNew.push($scope.hotels[i]);
console.log('hotelsNew',$scope.hotelsNew);
}
}
}
see the example for pushing array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
get length of data using
$s=Array.sizeof($data)
for($i<0;$i<=$s;$i++){//task here}

AngularJS, how to check if array contains duplicate values?

How do I check particularly using AngularJS if an array has duplicate values?
If more than 1 element of the same exist, then return true.
Otherwise, return false.
$scope.intArray = [5, 11, 17, 53] // return false because no duplicates exist
$scope.intArray = [5, 11, 17, 5] // return true because duplicaets exist
If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):
function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}
Otherwise:
function hasDuplicates(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}
Just sort the array and then run through it and see if the next index is the same as the current.
$scope.intArray = [5, 11, 17, 5];
checkDupes($scope.intArray);
function checkDupes(array)
{
array.sort(); // use whatever sort you want
for (var i = 0; o < array.length -1; i++)
{
if (array[i+1] == array[i])
{
return true;
}
}
return false;
}
http://codepen.io/anon/pen/xZrrXG?editors=101
Created the hasDuplicate as a scope method which could be easily used in your html if need-be.
var app = angular.module('myapp', []);
app.controller('mycontroller', ['$scope', function($scope) {
$scope.intArray = [5, 11, 17, 5];
$scope.hasDuplicate = function(data) {
for (var i = 0; i < data.length; i++) {
for (var x = i + 1; x < data.length; x++) {
if (data[i] == data[x]) {
return true;
}
}
}
return false;
};
}]);
You could use lodash library, you could find it very handy sometimes. And implement it like mentioned here: https://stackoverflow.com/a/28461122/4059878

advanced filter array angularjs

I'm trying to perform an advanced search with an angular filter. The idea of the filter is to receive two values (maximum and minimum) in an array and copy all intervals that are within the maximum and minimum of another array.
example:
array = {20,32,10, 60, 75, 43, 95}
minimum: 50
maximum: 100
resultant vector = {60, 95} 75.
code:
for (var i = 0; i < products.length; i++) {
if (product[i].precio >= $scope.minimo && product[i].precio <= $scope.maximo)
return this.products[i];
}
return null;
};
Something like:
angular.filter('someFilter', function() {
var newArray = [];
return function(products, min, max) {
for(var i = 0; i < products.length, i++) {
if (products[i].precio >= min && products[i].precio <= max) {
newArray.push(products[i]);
}
}
return newArray;
};
});
And use it like: <... ng-repeat="products | someFilter:min:max" ...>

Resources