Get numbers greater than n - javascript

I need to console.log every number that is greater than 10 from this row
[ 10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6]
I know it should be something like this
var row = [ 10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6];
for (var i = 0; i<row; i++)
{
console.log(niz[i]);
}

Well you could either use a for loop or mapping. For loop would be like this:
for (var i = 0; i<row.length; i++)
{
if (row[i] > 10)
console.log(row[i]);
}
To use mapping:
row.map(function(element){
if (element > 10)
console.log(element);
});

As you stated in the question, you need to use a for-loop to iterate trough all the items in your array. This is almost done correctly, but instead of doing i<row, you need to check against the length of the row (row.length).
In your case, i will be the index in your list, and it will increment with one (i++) in each iteration in the for-loop until you reach the number of items in rows.
The thing that you are missing is a if-statement to check if the item in the array is greater than 10.
I've tried to explain each line with a comment.
var row = [10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6];
var items = row.length; // number of items in your array
for (var i = 0; i < items; i++) { // iterate trough all the items
var numberInRow = row[i]; // the number with index number i in rows
var isGreaterThanTen = numberInRow > 10; // true if the number is greater than ten
if (isGreaterThanTen) { // will execute if isGreaterThanTen is true
console.log(numberInRow); // print number greater than 10 to console.
}
}

A forEach-loop seems a nice way of solving your problem:
var row = [ 10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6];
row.forEach(function(x){if(x>10){console.log(x)}})
or even shorter
[10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6].forEach(function(x){if(x>10){console.log(x)}})
The output in both cases:
11
12
156
61
89

Related

Sorting an array by their ascending value within the array in JS

It's a bit of a tricky situation I'm in, but I have an array like this:
const nums = [32, -3, 62, 8, 121, -231, 62, 13];
and need to replace them by their corresponding ascending index. The above example should yield:
[4, 1, 5, 2, 7, 0, 6, 3]
The solution I've come up with is this: TS Playground
const nums = [32, -3, 62, 8, 121, -231, 62, 13];
const numsCopy = nums.map(e => e);
// Basic sorting
for (let i = 0; i < numsCopy.length; i++) {
for (let j = 0; j < numsCopy.length; j++) {
if (numsCopy[i] < numsCopy[j]) {
let t = numsCopy[j];
numsCopy[j] = numsCopy[i];
numsCopy[i] = t;
}
}
}
for (let i = 0; i < numsCopy.length; i++) {
let sortedValue = numsCopy[i];
nums[nums.indexOf(sortedValue)] = i;
}
Problems arise however when I change nums to include a value nums.length > n >= 0. The call nums.indexOf(...) may return a faulty result, as it may have already sorted an index, even though it exists somewhere in the array.
If you replace nums with these values, -231 will have an index of 2 for some reason...
const nums = [32, -3, 62, 7, 121, -231, 62, 13, 0];
> [5, 1, 6, 3, 8, 2, 7, 4, 0]
Is there a better approach to this problem, or a fix to my solution?
You could sort the indices by the value and create a new array with index values a sorted positions.
to get the wanted result call the sorting function again and you get the indices sorted by the index order.
const
sort = array => [...array.keys()].sort((a, b) => array[a] - array[b]),
fn = array => sort(sort(array));
console.log(...fn([32, -3, 62, 8, 121, -231, 62, 13])); // 4 1 5 2 7 0 6 3
console.log(...fn([-1, 3, 1, 0, 2, 9, -2, 7])); // 1 5 3 2 4 7 0 6
Copy the array, sort its values, get indexOf, and null the value in the sorted copy:
const sortIndicesByValue = array => {
const sorted = [...array].sort((a, b) => a - b);
return array.map(e => {
const i = sorted.indexOf(e);
sorted[i] = null;
return i;
})
}
console.log(...sortIndicesByValue([32, -3, 62, 8, 121, -231, 62, 13]));
console.log(...sortIndicesByValue([-1, 3, 0, 0, 2, 9, -2, 7]));

Get the 5 items before and after the current index in an array

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));

Javascript Select vector with the greatest number of items [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 2 years ago.
Improve this question
I have 4 arrays:
Note: Length of array length is different in any session
var Class_A = [8, 11, 3, 9, 11, 16, 16];
var Class_B = [2, 6, 12, 13, 20, 22, 33, 40, 50, 66, 77]; // Greatest length with 11 items,
var Class_C = [10, 14, 19];
var Class_D = [8, 2];
I need to select array with greatest number of items, (Class_B)
My expectation is:
var major = number major of array.length (in this case Class_B);
My code:
var major = max(Class_A.length > Class_B.length > Class_C.length > Class_D.length);
Edit
An unorthodox solution, from a newbie but it works.
var Class_A = [8, 11, 3, 9, 11, 16, 54, 14, 5];
var Class_B = [2, 6, 12, 13, 20, 22, 33, 40, 50, 66, 77, 16, 7]; // Greatest length with 11 items,
var Class_C = [10, 14, 19];
var Class_D = [8, 2];
var Classes = [];
Classes.push(Class_A.length) ;
Classes.push(Class_B.length) ;
Classes.push(Class_C.length) ;
Classes.push(Class_D.length) ;
console.log("Lenght of 4 arrays>"+Classes);
Classes.sort(function(a, b) { // order by major number
return a - b;
});
Classes.reverse(); // reverse array
console.log("Total>"+Classes); // print sort by major number
console.log("Major>"+Classes[0]); // Works => the magic number that I need
Put all your arrays in an array.
classes = [Class_A, Class_B, Class_C, Class_D];
Then, to get the largest one:
classes.reduce((acc, curr) => curr.length > acc.length ? curr : acc);
// => [2, 6, 12, 13, 20, 22, 33, 40, 50, 66, 77]
EDIT:
Or, if you want length of the largest array:
classes.reduce((acc, curr) => curr.length > acc ? curr.length : acc, 0);
// => 11

Counting iterations of 1 in an array

My goal is to count iterations of 1 in an array.
I have this code:
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
var count = 0;
for(var i = 0; i < array.length; ++i){
if(array[i] === 1)
count++;
}
console.log(count);
Right now, it logs 5, but including "10" it should log 6, since "10" also contains a 1. What code can I use for this?
What about:
var count = array.toString().split('1').length - 1;
You can use filter method in combination with length property in order to write a more cleaner solution.
Also, use join and split methods in order to achieve your requirement.
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
console.log(array.join('').split('').filter(a=>a==1).length);
or using reduce method.
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
console.log(array.join('').split('').reduce((c,i)=> i==1 ? c+1 :c).length);
Just convert every item to string, and then check if 1 belongs to that number or not.
So for number 10, the string is '10' and then '10'.indexOf('1') equals to 0. So every time 1 is found within the string, you increment the counter.
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
var count = 0;
for (var i = 0; i < array.length; ++i) {
if (array[i].toString().indexOf('1') >= 0)
count++;
}
console.log(count);
You need to split your numbers into digits and iterate over each digit (which is a character) and compare with it. Use Object#toString to parse the number into the string, split into characters by String#split and using Array#forEach iterate over characters and do the same comparison there.
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
var count = 0;
for(var i = 0; i < array.length; ++i) {
var numberAsString = array[i].toString();
numberAsString.split('').forEach(char => {
if(char === '1') {
count++
}
});
}
console.log(count);
You'll need to convert each number to a string and use indexOf
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
var count = array.reduce(function(p,c){
if(c.toString().indexOf("1")>-1)
p++;
return p;
},0);
console.log(count);
You can Array#join the array items to a string and count using String#match with a regular expression:
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
// the || [] is a fallback in case there is no 1, and match returns null
var result = (array.join('').match(/1/g) || []).length;
console.log(result);
You could check every character of the joined string.
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1],
count = 0,
i,
temp = array.join('');
for (i = 0; i < temp.length; ++i) {
if (temp[i] === '1') {
count++;
}
}
console.log(count);
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
var count = 0;
for(var i = 0; i < array.length; ++i){
if( array[i] === 1 || array[i].toString().includes("1") )
count++;
}
console.log( count );

How to programmatically identify where n would fit in this sequence?

I have a number I want to conform to the closest value in the following sequence:
2, 5, 9, 12, 15, 19, 22, 25, 29, 32, 35, 39, 42...
If 10 is passed, it would become 12, 13 would become 15, 17 would become 19.
How would I approach this in a function?
If you don't know whether the array is sorted, you could use code like this to find the value in the array that is the closest to the passed in value (higher or lower):
var list = [2, 5, 9, 12, 15, 19, 22, 25, 29, 32, 35, 39, 42];
function findClosestValue(n, list) {
var delta, index, test;
for (var i = 0, len = list.length; i < len; i++) {
test = Math.abs(list[i] - n);
if ((delta === undefined) || (test < delta)) {
delta = test;
index = i;
}
}
return(list[index]);
}
If you want the closest number without going over and the array is sorted, you can use this code:
var list = [2, 5, 9, 12, 15, 19, 22, 25, 29, 32, 35, 39, 42];
function findClosestValue(n, list) {
var delta, index;
for (var i = 0, len = list.length; i < len; i++) {
delta = n - list[i];
if (delta < 0) {
return(index ? list[index] : undefined);
}
index = i;
}
return(list[index]);
}
Here is a jsFiddle with a solution that works for an infinite series of the combination "+3+4+3+3+4+3+3+4+3+3+4....." which seems to be your series. http://jsfiddle.net/9Gu9P/1/ Hope this helps!
UPDATE:
After looking at your answer I noticed you say you want the closes number in the sequence but your examples all go to the next number in the sequence whether it is closest or not compared the the previous number so here is another jsfiddle that works with that in mind so you can choose which one you want :).
http://jsfiddle.net/9Gu9P/2/
function nextInSequence(x){
//sequence=2, 5, 9, 12, 15, 19, 22, 25, 29, 32, 35, 39, 42
var i= x%10;
switch(i){
case 2:case 5:case 9: return x;
case 0:case 1: return x+ 2-i;
case 3:case 4: return x+5-i;
default: return x+9-i;
}
}
alert(nextInSequence(10))

Categories