Finding the index - javascript

I'm trying to get an odd number and even numbers in a given string, and the return value should be an index of the odd number or even number.
for example
oddOrEvenValue('2 4 9 6 10'); // => should return 3 as an index of odd number in the string
oddOrEvenValue('1 4 5 11'); // => should return 2 as an index of even number in the string
This is my code
const oddOrEvenValue = str => {
//convert the string into an array
let strToArr = str.split(' ');
//filtering the Even numbers
const evenNumbers = strToArr.filter(e => e % 2 === 0);
//filtering Odd numbers
const oddNumbers = strToArr.filter(od => od % 2 !== 0);
//comparing the even and odd arrays
if(Number(evenNumbers.length) > Number(oddNumbers.length)) {
return oddNumbers;
} else {
return evenNumbers;
}
}
console.log(oddOrEvenValue('2 4 9 6 10')); // => 3 is the index of an odd number
so i'm wondering how to get the index of an odd number instead of getting the the number itself?
const oddOrEvenValue = str => {
//convert the string into an array
let strToArr = str.split(' ');
//filtering the Even numbers
const evenNumbers = strToArr.filter(e => e % 2 === 0);
//filtering Odd numbers
const oddNumbers = strToArr.filter(od => od % 2 !== 0);
//comparing the even and odd arrays
if(Number(evenNumbers.length) > Number(oddNumbers.length)) {
return oddNumbers;
} else {
return evenNumbers;
}
}
console.log(oddOrEvenValue('2 4 9 6 10'));

Use the indexOf array method.
const oddOrEvenIndex = str => {
//convert the string into an array
let strToArr = str.split(' ');
//filtering the Even numbers
const evenNumbers = strToArr.filter(e => e % 2 === 0);
//filtering Odd numbers
const oddNumbers = strToArr.filter(od => od % 2 !== 0);
//comparing the even and odd arrays
if(evenNumbers.length > oddNumbers.length) {
return strToArr.indexOf(oddNumbers[0]);
} else {
return strToArr.indexOf(evenNumbers[0]);
}
}
console.log(oddOrEvenIndex('2 4 9 6 10'));
console.log(oddOrEvenIndex('1 4 5 11'));
The length property is always a number, there's no need to convert it with the Number() function.
Also, array indexes start from 0. If you want the result to be 1-based, add + 1 to the return statements.

Iterate over the whole array, check if value is odd or even, then store the index of that value into evenNumberIndexes/ oddNumberIndexes accordingly.
const oddOrEvenIndex = str => {
//convert the string into an array
let strToArr = str.split(' ');
let evenNumberIndexes = [];
let oddNumberIndexes = [];
// iterate over array
for (var i = 0; i < strToArr.length; i = i + 1) {
// CHeck if number is odd or even and add the index to the arrays accordingly
if (strToArr[i] % 2 ==0) {
evenNumberIndexes.push(i+1);
} else {
oddNumberIndexes.push(i+1);
}
}
// comparing the even and odd arrays
if(Number(evenNumberIndexes.length) > Number(oddNumberIndexes.length)) {
return oddNumberIndexes;
} else {
return evenNumberIndexes;
}
}
console.log(oddOrEvenIndex('2 4 9 6 10'));
console.log(oddOrEvenIndex('1 4 5 11'));
console.log(oddOrEvenIndex('2 4 9 6 10 8 9 9 6 6'));

Related

Javascript how to round a whole number up and find its addition value?

Goal
I am at the final stage of scripting a Luhn algorithm.
Problem
Let's say I have a final calculation of 73
How can I round it up to the next 0? So the final value is 80.
And lastly, how can I get the value that made the addition? e.g. 7 is the final answer.
Current code
function validateCred(array) {
// Array to return the result of the algorithm
const algorithmValue = [];
// Create a [2, 1, 2] Pattern
const pattern = array.map((x, y) => {
return 2 - (y % 2);
});
// From given array, multiply each element by it's pattern
const multiplyByPattern = array.map((n, i) => {
return n * pattern[i];
});
// From the new array, split the numbers with length of 2 e.g. 12 and add them together e.g. 1 + 2 = 3
multiplyByPattern.forEach(el => {
// Check for lenght of 2
if(el.toString().length == 2) {
// Split the number
const splitNum = el.toString().split('');
// Add the 2 numbers together
const addSplitNum = splitNum.map(Number).reduce(add, 0);
// Function to add number together
function add(accumalator, a) {
return accumalator + a;
}
algorithmValue.push(addSplitNum);
}
// Check for lenght of 1
else if(el.toString().length == 1){
algorithmValue.push(el);
}
});
// Sum up the algorithmValue together
const additionOfAlgorithmValue = algorithmValue.reduce((a, b) => {
return a + b;
});
// Mod the final value by 10
if((additionOfAlgorithmValue % 10) == 0) {
return true;
}
else{
return false;
}
}
// Output is False
console.log(validateCred([2,7,6,9,1,4,8,3,0,4,0,5,9,9,8]));
Summary of the code above
The output should be True. This is because, I have given the total length of 15 digits in the array. Whereas it should be 16. I know the 16th value is 7, because the total value of the array given is 73, and rounding it up to the next 0 is 80, meaning the check digit is 7.
Question
How can I get the check number if given array length is less than 15?
You could do something like this:
let x = [73,81,92,101,423];
let y = x.map((v) => {
let remainder = v % 10;
let nextRounded = v + (10-remainder);
/* or you could use
let nextRounded = (parseInt(v/10)+1)*10;
*/
let amountToNextRounded = 10 - remainder;
return [nextRounded,amountToNextRounded];
});
console.log(y);
EDIT
As noticed by #pilchard you could find nextRounded using this more simplified way:
let nextRounded = v + (10-remainder);
https://stackoverflow.com/users/13762301/pilchard
I think what you need is this:
var oldNum = 73
var newNum = Math.ceil((oldNum+1) / 10) * 10;;
Then check the difference using this:
Math.abs(newNum - oldNum);

creating a function that only returns odd numbers [duplicate]

This question already has answers here:
How do I extract even elements of an Array?
(8 answers)
How to do a script for odd and even numbers from 1 to 1000 in Javascript?
(8 answers)
Closed 2 years ago.
I've spent an embarrassing amount of time on this question only to realize my function is only right 50% of the time. So the goal here is to return only the odd numbers of all the numbers in between the two arguments. (for instance if the arguments are 1 and 5 i'd need to return 2 & 3) the function I wrote is completely dependent on the first argument. if it's even my function will return odds, but if the first number is odd it'll return evens. does anyone know how i can fix this?
function oddNumbers(l, r) {
const arr = [];
const theEvens = [];
for (let i= l; i<r; i++) {
arr.push(i)
}
console.log(arr)
for (let i= 0; i < arr.length; i+= 2 ) {
const evens = arr[0] + i;
theEvens.push(evens);
}
theEvens.forEach(item => arr.splice(arr.indexOf(item), 1));
console.log(arr)
}
oddNumbers(2, 20);
I modified the code a bit to return only odd numbers
We use the % operator that behaves like the remainder operator in math:
so when we say i % 2 if the number is even the result of the operation will be 0
but when the "i" is an odd number the result will be 1
so now we can filter the even from the odd numbers using this operation
function oddNumbers(l, r) {
const arr = [];
for (let i= l; i<r; i++) {
if(i % 2 !== 0) arr.push(i);
}
console.log(arr);
}
oddNumbers(2, 20);
You can loop from initial to end parameters and get odd numbers using modulo, try this:
let result = [];
let returnOdd = (n1, n2) => {
for(i = n1; i < n2; i++){
if(i % 2 != 0){
result.push(i)
}
}
return result;
}
console.log(returnOdd(2, 20));
You could use the filter method.
This method creates a new array based on the condition it has. In this case it will to go through all the numbers in the array, and check if the number is odd (though the remainder operator).
For example:
1 % 2 = 1 ( true, keep in the new array )
2 % 2 = 0 ( false ignore in the new array )
function OddNumbers(start, end) {
// Create an array from the given range
const nums = Array(end - start + 1).fill().map((_, idx) => start + idx);
// Use filter to return the odd numbers via the % operator
return nums.filter(num => num % 2);
}
console.log(OddNumbers(2,20))

if Input: 8-e Expected Output: 2|4|6|8

Question 2: The input consist of a string, "o" represents odd number, "e" represents even number to be printed
Example 1.
Input: 8-e
Expected Output: 2|4|6|8
Example 2.
Input: 6-o
Expected Output: 1|3|5
Example 3.
Input: 1-o
Expected Output: 1
if have tried with for loop, but I'am a beginner so I'am confused with(-e)
const evenOdd = (number) => {
let evenvalue = [];
let oddValue=[];
for(let i =0; i<=number; i++){
if(number%i==0)
evenvalue.push(i);
console.log(evenvalue);
}if(number%i!=0){
oddValue.push(i);
console.log(oddValue);
}
};
evenOdd(9);
You could take a while statement and get a start value of one plus an offset of one if the wanted type is even. Then iterate and add the value to the result set until the value is greater than the maximum value.
function fn(request) {
var [max, type] = request.split('-'),
i = 1 + (type === 'e'),
result = [];
while (i <= max) {
result.push(i);
i += 2;
}
return result;
}
console.log(...fn('8-e'));
console.log(...fn('6-o'));
console.log(...fn('1-o'));
You will need to extract the letter and the number from you string first. One easy way to do that :
const evenOdd = (s) => {
let odd = s.length-1 ==='o';
let number = Number(s.substring(0, s.length-2));
let evenvalue = [];
...
if(odd){...} else {...}
};
You could also use split() or if the pattern was more complicated, a Regex.
You can split on - and add based on type add values upto the number
Split the given input by -, first value represents max number and second represents it's type
Check the type if it is even add the even values start from 2 and upto to the max number else start from 1, and join them with | in the end
let func = (input) => {
let [num, type] = input.split('-')
let arr = []
let i = 1 + (type === 'e')
while (i <= num) {
arr.push(i)
i += 2
}
return arr.join('|')
}
console.log(func('8-e'))
console.log(func('1-o'))
console.log(func('6-o'))
Basically, don't supply a number to the function, supply a string and then parse the string. That is, don't try and give the function 9-e, give it '9-e'.
Get the parts of the input by splitting on -.
Turn the number into a number.
Give 0 for even, 1 for odd (x % 2 is 0 for even number, 1 for odd).
Build the results.
function listNumbers(constraint)
{
const parts = constraint.split('-');
const number = Number(parts[0]);
const numberType = parts[1] === 'e' ? 0:1;
let result = [];
for(let i = 1; i <= number; i++)
{
if(i%2 === numberType)
{
result.push(i);
}
}
return result;
}
console.log(listNumbers('8-e'));
Or if you want make the code look clever:
function listNumbers(constraint)
{
const parts = constraint.split('-');
const number = Number(parts[0]);
const numberType = parts[1] === 'e' ? 0:1;
return Array.from(Array(number), (x,i) => i + 1 ).filter(x => x%2 == numberType);
}
console.log(listNumbers('8-e'));

Print the value of the first element that occurs N number of times

So I'm making this ReactJS application.
Part of a filtering system I have the following problem:
Simplified...
I have an array, let's say its simple one like let arr = [1,7,4,3,4,7];
and I also input an N variable from the user that is a simple integer input.
I need to return or console.log() the integers from the array that is repeated N times. If there is nonsuch repeating number log err msg or return -1;
For instance,
let arr = [1,7,4,3,4,7]; and let n = 2; i get 7- cos 7 repeats 2 times
let arr = [7,4,5,3,5,5,3,4,3,2,1]; and let n = 3; i get 5 - cos 5 repeats 3 times
let arr = [1,6,4,6,4,6]; and let n = 4; i get -1 or cl("err") - cos nothing repeats 4 times
Code from comments:
const getRepeatingNumber = (arr, n) => {
for (unit of arr) {
if (unit === maj_unit) count++;
else {
count--;
if (count === 0) {
maj_unit = unit;
count = 1;
}
}
}
return maj_unit;
}
You can use array#every, create an accumulator and place the number as key and its frequency as value, once the value reaches the specified number of occurrence, break from the loop using return false, then return the result.
const getRepeatingNumber = (arr, count) => {
let result = -1, hash = {};
arr.every(n => {
hash[n] = (hash[n] || 0) + 1;
if(hash[n] === count) {
result = n;
return false;
}
return true;
});
return result;
}
console.log(getRepeatingNumber([1,7,4,3,4,7],2));
console.log(getRepeatingNumber([7,4,5,3,5,5,3,4,3,2,1], 3));
console.log(getRepeatingNumber([1,6,4,6,4,6], 4));
Below is the code which will fix your problem I hope.
You need to loop over all array values and find how many time each value occurred and save number of occurrence in a result array because there may be multiple values occurred n number of times. i.e. in your provided array let arr = [1,7,4,3,4,7]; 7 and 4 occurred twice but i am returning result[0] since you might only need first occurred value for n times.
let arr = [1,7,4,3,4,7];
let getRepeatingNumber = function (arr, n) {
let result = [];
arr.forEach((value) => {
if (arr.filter(val => val === value).length === n && !result.includes(value)) {
result.push(value);
}
});
return result.length ? result[0] : -1
}
console.log(getRepeatingNumber(arr, 2)); // 7

Unable to compare two values in an array for javascript

I am trying to see if I can get my function to determine the "odd man out" in the array living within the function. Specifically, after I take a string, convert it into numbers and push it into an array -- I want it to be able to loop through the output array and return the index of which number is "the odd man out" (i.e. "2 2 2 2 4 6 8 1" should return index 7 as it is the only odd number). However, I'm having trouble figuring out how to return the index, when the function faces both situations that I listed below in the code.
function notSame(numbers){
var notString = parseInt(numbers.replace(/\s+/g, ''), 10),
sNumber = notString.toString(),
output =[];
console.log(sNumber);
for(var i = 0; i < sNumber.length; i+=1) {
output.push(+sNumber.charAt(i));
}
for(var num1 = 0; num1 < output.length; num1++) {
for(var num2 = 1; num2 < output.length; num2++) {
if(output[num1] % output[num2] === 1) {
return num1;
}
}
}
}
notSame("2 2 2 2 4 6 8 1"); /// Situation 1: should output index 7 as it is the only odd number
notSame("5 7 9 2 1" ); ///Situation 2: should output index 4 as it is the only even number
Once you have your integers in the output array,
// test the first three array members
var test = Math.abs(output[0])%2 + Math.abs(output[1])%2 + Math.abs(output[2])%2;
// if the sum of the mods of the first three integers in the
// array is more than 1, the array is mostly odd numbers, hence
// the odd one out will be even, else it will be odd
var outlierIsOdd = test >= 2 ? false : true;
// find the odd one out and return it's index
return output.indexOf(output.filter(function(e){
return (Math.abs(e)%2 === +outlierIsOdd);
})[0]);
You might find it easier to break down the problem into smaller units.
// return an array from a string
function toArray(str) { return str.split(' '); }
// return the element if it's even
function even(el) { return el % 2 === 0; }
// return the index of either true/false
function getIndex(arr, flag) { return arr.indexOf(flag); }
// count how many instances of true are in the array
function count(arr) {
return arr.filter(function (el) {
return el;
}).length;
}
function check(str) {
// return an array of true/false values
var evens = toArray(str).map(even);
// if there is more than 1 true value in `evens`
// return the index of false from the array
// otherwise return the index of the only true element
return count(evens) > 1 ? getIndex(evens, false) : getIndex(evens, true);
}
check('2 2 2 2 4 6 8 1'); // 7
check('5 7 9 2 1'); // 3
check('2 5 2 6 6'); // 1
check('7 7 7 9 1 3 8 1 5') // 6
DEMO
function notSame(string) {
var even = [];
var odd = [];
string.split(" ").forEach(function(e, i) {
string.split(" ")[i] % 2 ? odd.push(i) : even.push(i);
})
even > odd ? document.write(even) : document.write(odd);
}
notSame("2 2 2 2 4 6 8 1");
Fill up 2 arrays with index:
one for odds and one for evens and compare the length.

Categories