I have an array of randomly generated numbers.
I want to create a function that divides all those numbers. Basically, assuming that I have 5 numbers in the array [5, 7, 6, 8, 2], I want the output to be equal to 5 / 7 / 6 /8 / 2
array = [5, 7, 6, 8, 2];
var total = 1;
for(var i = 0; i < array.length; i++) {
total = array[i] / total;
}
return total;
This is what I did so far, but the output isn't the correct one. Any idea where I am doing wrong?
You've basically got your math backwards. With your approach, you want to progressively divide total, rather than progressively dividing by total.
var total = array[0];
for (var i = 1; i < array.length; i++)
total = total / array[i];
return total;
Try this. It uses the array's reduce method along with es6 arrow functions which makes it a one liner. You can use babel to convert es6 syntax to es5.
var arr = [5, 7, 6, 8, 2];
arr.reduce((prev,curr) => prev/curr);
ES5 version:
var arr = [5, 7, 6, 8, 2];
arr.reduce(function(prev, curr) {
return prev/curr;
});
As you can see in the docs, Array.reduce() will reduce a list of values to one value, looping through the list, applying a callback function and will return a new list. In that callback you can access four parameteres:
previousValue: If you pass an argument after callback function, previousValue will assume that value, otherwise it'll be the first item in array.
currentValue: The current value in the loop.
index: Index of the current item on loop.
array: The list
Well you messed up with the total, you kept dividing each new number with the result. You just have to flip the '/' operators.
array = [5, 7, 6, 8, 2];
var total = array[0];
for(var i = 1; i < array.length; i++) {
total = total/array[i];
}
return total;
Try this ...
array = [5, 7, 6, 8, 2];
var total = array[0];
for(var i = 1; i < array.length; i++) {
total = array[i] / total;
}
return total;
Related
I have an array
const array = [6,2,6,7,5,9];
I want sum of all numbers till 7 in array
I tried .reduce but it gave me sum of whole array,
How can I do that so?
You're going to have to jump through a lot of hoops with reduce. You'd need to find the index of 7, then splice up to that index, and then reduce over the spliced array. Muy complicado!
It's much simpler to create a sum variable, and loop over the array. Add each number to the sum, and when the number is 7 break the loop.
It's worth noting this strategy wouldn't work for duplicate numbers like 6 for example because which 6 would you choose?
const arr = [6, 2, 6, 7, 5, 9];
let sum = 0;
for (const n of arr) {
sum += n;
if (n === 7) break;
}
console.log(sum);
This is doable with just a for loop:
const array = [6, 2, 6, 7, 5, 9];
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i];
if (array[i] == 7) break;
}
// outputs the sum of [6,2,6,7], which is 21
console.log(sum);
Here we take the sum of numbers till 7 to mean the sum of all numbers in our array up until the first instance of 7.
Try using this. This is going to loop trow and store the sum until it's 7.
const array = [6, 2, 6, 7, 5, 9]
let sum = 0
array.forEach((number) => {
if (sum <= 7) sum += number
})
console.log(sum) // Output: 8
Do write the following code before you reduce it!
const arr1 = array.slice(0,4);
and then reduce arr1. you will get your desired Answer!
oh and please change the name of the constant however you want!
Here you go,
const array = [6, 2, 6, 7, 5, 9];
const found = array.find(element => element >= 7);
const newArr = array.indexOf(found);
const arr1 = array.slice(0,(newArr + 1));
const sum = 0;
const result = arr1.reduce(
(previousValue, currentValue) => previousValue + currentValue,
sum
);
console.log(result); //output 21
I'm learning for loops in JS and am trying to learn how to console.log the first and last element in an array on one iteration, then console.log the second and second to last elements, etc.
here's what I have tried:
for (let i=0; i<myArray.length; i++){
console.log(myArray[i]);
console.log(myArray[i-1];
}
This is printing elements from my array, but not in the correct order
So what you are trying to achieve is to print the last element, the second last element, etc...
You can use the myArray.length property to do it, just substract the iterator + 1 to the array length and obtain the result you want.
for (let i=0; i<myArray.length; i++){
console.log(myArray[i]);
console.log(myArray[myArray.length - (i + 1)]);
}
The (i + 1) is because the .length property returns the number of item of the array, but not the maximum index of the array. So if the length of the array is 5, the maximum index of the array is 4 (since index starts from 0). You can also write it like: myArray[myArray.length - i - 1]
Here an example:
const myArray = [1, 2, 3, 4, 5];
for (let i=0; i<myArray.length; i++){
console.log(myArray[i]);
console.log(myArray[myArray.length - (i + 1)]);
}
Create a temporary copy of your array, then use shift (to remove the head element) and pop (to remove the tail element) until the copy is empty:
const realArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const temporary = realArray.slice();
while (temporary.length) {
const e1 = temporary.shift();
// do something with e1
console.log(e1);
const e2 = temporary.pop();
if (e2) {
// note that e2 _might not exist_ so: always test
console.log(e2);
}
}
You can use two counters that works on opposite direction
i will move forward with increment as i++.
j will move backward with decrement as j--.
If there are even numbers of elements in an array then you should print both numbers arr[i] and arr[j]. But be sure to handle the odd number of elemetns in an array then you have to print either of arr[i] or arr[j]
function print(arr) {
let i = 0;
j = arr.length - 1;
while (i <= j) {
if (i !== j) {
console.log(arr[i], arr[j]);
} else console.log(arr[j]);
i++;
j--;
}
}
print([1, 2, 3, 4, 5, 6, 7, 8]);
print([1, 2, 3, 4, 5, 6, 7, 8, 9]);
Here's one way to do it, reverse the array and use the same index. Since array.reverse() mutates the original array, we slice() it in order to use a copy.
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
array.forEach((a, i) => {
let b = array.slice().reverse()[i]
if (i < array.length / 2) console.log(a, b)
})
let output = '';
for (let i = 0; i < (myArr.length) /2; i++){
output += myArr[i] + myArr[myArr.length-1-i];
}
console.log(output)
Just check for i === 0 to indicate the start of the loop and hence, you can print the last element of array
const myArray = ['first', 1, 2, 3, 'last'];
for (let i = 0; i < myArray.length - 1; i++) {
console.log(myArray[i]);
if (i === 0) {
console.log(myArray[myArray.length - 1]);
}
}
I'm trying to find the second largest number in an array of numbers, but the greatest number appears twice, so I can't just remove it from the array and select the new highest number.
array = [0, 3, 2, 5, 5] (therefore 3 is the 2nd largest value)
I have this code where I can explicitly return 3, but it wouldn't work on other arrays:
function getSecondLargest(nums) {
var sorted_array = nums.sort(function (a,b) {return a - b;});
var unique_sorted_array = sorted_array.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
return unique_sorted_array[unique_sorted_array.length - 2];
}
return unique_sorted_array[unique_sorted_array.length - 2];
If I wanted to make it more dynamic, is there a way that I could identify the greatest value of the array, then compare that against each iteration of the array?
I was thinking that something along the lines of:
var greatestNum = sortedArray[-1]
while(greatestNum != i) do {
//check for the first number that doesn't equal greatestNum
}
Any help would be appreciated.
You can simply create a Set first and than sort in descending and take the 1st index element
let array = [0, 3, 2, 5, 5]
let op = [...new Set(array)].sort((a,b) => b-a)[1]
console.log(op)
For those who thinks in terms of efficiency. this is the best way IMO
let array = [0, 3, 2, 5, 5]
let max = -Infinity
let secondMax = -Infinity
for(let i=0; i<array.length; i++){
if(array[i] > max){
secondMax = max
max = array[i]
}
}
console.log(secondMax)
I’d recommend doing something more like
const nums = [0, 3, 2, 5, 5];
nums.sort(function (a,b) {return b - a;})
for (let i = 1; i < nums.length; i++) {
if (nums[0] !== nums[i]) {
return nums[i];
}
}
which should be a lot more efficient (especially in terms of memory) than converting to a set and back...
Try this:
var intArray = stringArray.map(nums); // now let's sort and take the second element :
var second = intArray.sort(function(a,b){return b-a})[1];
};
For those who wants to do this using Math.max(). Here's the simplest way to do this.
const getSecondLargest = function (arr) {
const largest = Math.max.apply(null, arr);
for (let i = 0; i < arr.length; i++) {
if (largest === arr[i]) {
arr[i] = -Infinity;
}
}
return Math.max.apply(null, arr);
};
console.log(getSecondLargest([3, 5, 9, 9, 9])); //5
Side note: Math.max() don't take an array, so we have to use Math.max.apply() to pass the array in the function. -Infinity is smaller than any negative finite number.
The following is my code, so far I keep receiving NaN.
function yo() {
var numbers = new Array([4, 5, 7, 2]);
var total = 0;
for(var i = 0; i < numbers.length; i++) {
total += numbers[i];
}
var avg = total / numbers.length;
console.log(avg);
alert(avg);
return avg;
}
yo();
What's wrong with my code?
Remove [] at call to new Array() which returns an array using parameters passed. new Array([]) returns an array within an array.
var numbers = new Array(4, 5, 7, 2);
function yo() {
var numbers = new Array(4, 5, 7, 2);
var total = 0;
for (var i = 0; i < numbers.length; i++) {
total += numbers[i];
}
var avg = total / numbers.length;
console.log(avg);
alert(avg);
return avg;
}
yo();
change this line from
var numbers = new Array([4, 5, 7, 2]); to var numbers = [4, 5, 7, 2];
Here your problem is that you are creating an array within an array
try console.log(numbers)
If you want to use the new Array syntax you don't need [] inside of it in order to return a proper 1 dimensional array.
You've initialized numbers as an Array of an Array of 3 elements.
In your code, numbers is [[4, 5, 7, 2]], when you're probably expecting it to be numbers = [4, 5, 7, 2].
You could change the numbers assignment to read:
var numbers = new Array(4, 5, 7, 2); // remove the brackets
// or
var numbers = [4, 5, 7, 2];
I search everywhere here but couldn't find the answer...only some pieces of it..
I got an interview question...
You have an array and it's array.length=9. You have 10 numbers, from 1 to 10. Put those numbers randomly to Array. How to find/return the number what leftover and not got to the Array.
Any solutions?
Try the following code:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var chosen = [];
for(var i = 0; i < 9; i ++){
var index = Math.floor((Math.random() * numbers.length) + 1)-1;
chosen.push(numbers[index]);
numbers.splice(index, 1);
}
document.write(JSON.stringify(chosen)+"<br>");
document.write(numbers);
using array.indexOf() method you can do it.
first creat random array arr then do this:
for(var i=1;i<=10;i++){
if(arr.indexOf(i)==-1){
console.log(i+'is not in the array');
return i;
}
}