So I wanted to choose an array index based off its percentage in the array.
The "percentage in the array" is just a function of the index, so like for an 11-element array the 50% index would be 5.
const numbers = [0 , 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
I imagine I'd want to first go ahead by grabbing the length of the array to have a solid number to work a percentage from.
numbers.length; // 14
Though how would I then go about using a percentage to go into the array using the length to select an index that NEAREST matches the percentage? For example if I wanted to select the index that was nearest to being on 25% of the array?
I think you are looking for something like this.
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
const percentage = 50
let indexAtPercentage = Math.round((numbers.length - 1) * percentage / 100)
console.log("index: " + indexAtPercentage + "\nnumber at index: " + numbers[indexAtPercentage])
You can calculate the index or value of a given percentage by subtracting one from the length of the array, multiplying it by the percentage, and finally flooring the result.
The percentage parameter should be a value between 0.00 (0%) and 1.00 (100%).
const
indexOfPercent = (arr, percent) => Math.floor((arr.length - 1) * percent),
valueOfPercent = (arr, percent) => arr[indexOfPercent(arr, percent)];
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
for (let i = 0; i < numbers.length; i++) {
const
percent = i / (numbers.length - 1),
index = indexOfPercent(numbers, percent),
value = valueOfPercent(numbers, percent);
console.log(`${i} ${percent.toFixed(2)} ${index} ${value}`);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
I believe it is as clear as calculating the required index by getting the desired percentage mark from the length.
const numbers = [0 , 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let desiredPercentage = 25;
if (desiredPercentage) {
let indexAtPercent = Math.floor(numbers.length * desiredPercentage / 100);
if (indexAtPercent)
indexAtPercent--;
console.log(numbers[indexAtPercent]);
}
Related
I have to create two 10-elements arrays with random values from 1 to 20 and write a program that prints the largest value that occurs simultaneously in both arrays.
I created two tabs like below. The program should prints the largest value that occurs simultaneously in both arrays. Here it should be 11. I know just how to catch the max value from the array. I appreciate help.
<script>
var max = 0;
var tab = [1, 2, 5, 8, 9, 11, 15, 16, 17, 20];
var tab2 = [3, 4, 6, 7, 10, 11, 12, 13, 14, 18];
for (var i = 0; i < tab.length; i++) {
if (max <= tab[i]) {
max = tab[i];
}
}
console.log(max);
</script>
to find the largest value use nested loops to compare each element of both arrays as follow
var tab = [1, 2, 5, 8, 9, 11, 15, 16, 17, 20];
var tab2 = [3, 4, 6, 7, 10, 11, 12, 13, 14, 18];
var max = 0;
for (var i = 0; i < tab.length; i++) {
for (var j = 0; j < tab2.length; j++) {
if (tab[i] === tab2[j] && tab[i] > max) {
max = tab[i];
}
}
}
console.log(max);
I'd do this:
// const {intersection,max} require('lodash/fp'}
const { intersection, max } = _;
const tab = [1, 2, 5, 8, 9, 11, 15, 16, 17, 20];
const tab2 = [3, 4, 6, 7, 10, 11, 12, 13, 14, 18];
const res = max(intersection(tab, tab2))
console.log({
intersection: intersection(tab, tab2),
max: max(intersection(tab, tab2)),
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
You can translate that into straight javascript, especially if it's for a homework assignment :).
The approach is as follows ...
get the intersection of both arrays
get the maximum value of the just computed intersection
... which then boils down either to coming up with an own implementation of an intersection functionality or to making use of a third party library / helper functionality.
The below example code features one possible implementation of getIntersection which makes use of ...
Array.from in order to always ensure the processing of array parameters,
Array.prototype.sort in order to help optimally assign the participating arrays for the best computation performance,
Array.prototype.reduce and a Map instance for creating a lookup-table in order to achieve a more performant filter process when it comes to the actual computation of the intersection,
Array.prototype.filter and Map.prototype.has for finally computing the intersection result.
function getIntersection(firstIterable = [], secondIterable = []) {
const [
comparisonBase, // ... compare to the shorter array.
comparisonList, // ... filter from the longer array.
] = [Array.from(firstIterable), Array.from(secondIterable)]
// - ensure two arrays (line above)
// - and sort them according to each array's `length`.
.sort((a, b) => a.length - b.length);
// create a `Set` based lookup from the shorter array.
const itemLookup = new Set(comparisonBase);
// the intersection is the result of following filter task.
return comparisonList.filter(item => itemLookup.has(item));
}
const tab = [1, 2, 4, 5, 8, 9, 11, 15, 16, 17, 20, 21, 0];
const tab2 = [3, 4, 6, 7, 9, 10, 11, 12, 13, 14, 18, 19, 0];
console.log(
'intersection of `tab` and `tab2` ...',
getIntersection(tab, tab2)
);
console.log(
'max value of the intersection of `tab` and `tab2` ...',
Math.max(...getIntersection(tab, tab2))
);
Say I have an array that looks like this
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
These array represents page numbers in my scenario.
Say if I am on page 8, I'd like to create a seperate array that includes the following
The first 5 before page 8 and the first 5 after page 8.
i.e first 11 items array.
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Therefore having 11 items in an array including that page itself.
If the array is smaller than 5, then simply return the rest.
i.e
if the array looks like this [2,3,4,5,6,7,8]
and if the page is 4, since the before does not have 5 items exactly I'd like to get all of it.
You can use the slice method of the Array.
function paginatorNumbers(arr, currentIndex) {
return arr.length > 5 && currentIndex > 5
? arr.slice(currentIndex - 6, currentIndex + 5)
: arr.slice(0, currentIndex + 5)
}
Use the slice function. Given x=8 in your example, the following will create a new array with the indexes you want.
arr.slice(x-5, x+6)
The start index x-5 is inclusive (or it will include index 8-5 = 3). The end index x+6 is exclusive (it will not include index 8+6=14). So you get indices 3 - 13 like you wanted.
EDITED:
This should work now
const getRange = (array, index) => {
// You need constraints if index - 5 is < 0
const startIndex = Math.max(0, index - 5 - 1);
const endIndex = index+ 5;
return array.slice(startIndex, endIndex);
}
You can makeit very simple with Plus and Minus.
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
function getRange(current) {
let start = (current -5)
let end = (current + 5)
let res = []
start = start < 0 ? 0 : start
for(start; start <= end; start++) {
res.push(start)
}
return res;
}
console.log(getRange(8)) // starts from 3
console.log(getRange(2)) // starts from 0
Using the slice method, you can get a specific subarray from the whole array. What you need to do is to slice 5 places before the page index, and then slice 5 places after the page index. Then, just concat both subarrays and get the result.
The Math.min and Math.max functions are to avoid range problems when slicing the array. So, when the subarray is smaller than 5, it just returns the rest of the array, and not an empty array.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
let currentPage = parseInt(prompt("Current page"));
// page index
let i = arr.indexOf(currentPage);
// Using Math.max and Math.min to avoid range problems
const subarr = arr.slice(Math.max(i - 5, 0), i).concat(
arr.slice(i, Math.min(i + 6, arr.length)));
console.log(subarr);
This is a universal solution
count of items before and after can be set
.slice() is used for timming the array
checks that start index is not < 0 (otherwise it would be sliced from the end)
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
function getBeforeAfter(arr, index, count) {
let start = index - count -1
if(start < 0) start = 0
let end = index + count
return arr.slice(start, end)
}
console.log(getBeforeAfter(arr,8,5)) // [3,4,5,6,7,8,9,10,11,12,13]
You can use array#slice to generate number in a range relative to index.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
getRangeItem = (arr, index, range) => {
const start = Math.max(index - range - 1, 0),
end = Math.min(index + range, arr.length),
result = arr.slice(start, end);
return result;
}
console.log(getRangeItem(arr, 8, 5));
I have an array with some numbers like the following:
[1, 2, 3, 4, 6, 7, 8, 10, 15, 16, 17]
I'd like to show all numbers that are direct after each other (n+1) in one line and if there is a gap, this should be separated. This will either be done in javascript/jquery.
The user would see it like this:
1 - 4, 6 - 8, 10, 15 - 17
I'm guessing the only solution to this would be to loop through the array and see if the next number is n+1 and if it is, lump it together, else start on a new series?
I think I know how I would do it that way but interested to know if there is some other way to do it either in javascript/jquery?
You can loop once while keeping track of the current starting number.
let arr = [1, 2, 3, 4, 6, 7, 8, 10, 15, 16, 17];
let start = arr[0],
res = [];
for (let i = 1; i < arr.length; i++) {
if (arr[i + 1] - arr[i] != 1 || i == arr.length - 1) {
res.push(start + " - " + arr[i]);
start = arr[i + 1];
}
}
console.log(res);
var valid1=[4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
function validateCred(array) {
let doubleArray =0
for(i=array.length-2; i >= 0; i-=2) {
doubleArray= array[i]*2
}
console.log(doubleArray);
}
validateCred(valid1) //prints 8 I want it to print entire loop
Im trying to code luhn Algorithm and this is the first step of doubling every second number from the back, i want my result to equal doubleArray however when i try print it only 8 prints
you have only 8 prints because you have step i-2. Also, see comments in code about reversing an array
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
function validateCred(array) {
let doubleArray = [];
// we should move through all iterations that is why step i-=1
for(let i = array.length-1; i >= 0; i -= 1) {
// moving from the end of the array we will get reversed copy if using method push()
// that is why changed to unshift()
doubleArray.unshift((array.length - 1 - i) % 2 == 0 ? array[i] * 2 : array[i]);
// array.length - 1 - i - using because we need to move from right in case length not odd
}
console.log(doubleArray);
}
// ES6+ syntax version version
function esValidateCred1(array) {
const doubleArray = array.reverse().map((i, ind) => ind % 2 === 0 ? i*2 : i).reverse();
console.log(doubleArray);;
}
validateCred(valid1);
esValidateCred1(valid1);
You can refer the code below to get the desired output i.e. the an array with doubled value starting from back.
var valid1=[4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
function validateCred(array) {
let doubleArray = [];
for(i=array.length-2; i >= 0; i-=2) {
doubleArray.push(array[i] * 2)
}
return(doubleArray);
}
console.log(validateCred(valid1))
the easiest way is to use .map() method for array
var valid1=[4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
function validateCred(array) {
return array.map(item => item*2);
}
console.log( validateCred(valid1) ) //prints array doubled elements
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const output = move(numbers, 3, -5);
console.log(output);
function move(array, index, offset) {
const output = [...array];
const element = output.splice(index, 1)[0];
output.splice(index + offset, 0, element)
return output;
}
The first line is an array of numbers.
At the second line, when calling the move function, we pass three arguments.
First, is the array itself called numbers.
Secondly, the index of the number we are trying to move (in the example, we have index 3 so we are passing the number 4).
Finally, we have the offset set to -5. The negative sign means we are moving the number to the left. The 5 means 5 positions.
But as you can see, we only have 3 positions to the left of the number 4 before reaching the beginning of the array. In this case, we have to go to the end of the array and count backwards. So, we are looking for a function which will turn the original array to [1, 2, 3, 5, 6, 7, 8, 4, 9].
As you can see, number 4 has shifted 3 positions to the left to reach the beginning of the array, then, 2 further positions from the end of the array.
A further example to clarify.
Let's say we write:
const output = move(numbers, 1, -4);
In this example, we want the number 2 from the array (index 1) to move 4 positions to the left. So, we should get [1, 3, 4, 5, 6, 7, 2, 8, 9].
You need to cover the edge cases when the updated index is less than 0 OR greater than the array length. You can try following
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function move(array, index, offset) {
const output = [...array];
const element = output.splice(index, 1)[0];
let updatedIndex = index + offset;
if(updatedIndex < 0) updatedIndex++;
else if (updatedIndex >= array.length) updatedIndex -= array.length;
output.splice(updatedIndex, 0, element);
return output;
}
console.log(move(numbers, 3, -5));
You could do this using while loop and iterating for the Math.abs() of the position you want to move to and then move in direction depending if parameter is positive or negative.
function move(arr, i, p) {
let left = p < 0,
counter = Math.abs(p),
newPos = i;
while (--counter > -1) {
newPos = (left ? (newPos - 1) : (newPos + 1));
if (newPos == -1) newPos = arr.length - 1;
if (newPos == arr.length) newPos = 0;
if (counter == 0) arr.splice(newPos, 0, arr.splice(i, 1)[0])
}
return arr;
}
console.log(move([1, 2, 3, 4, 5, 6, 7, 8, 9], 3, -5));
console.log(move([1, 2, 3, 4, 5, 6, 7, 8, 9], 5, 5));
console.log(move([1, 2, 3, 4, 5, 6, 7, 8, 9], 1, -25));