odd to even numbers in an array javascript [duplicate] - javascript

This question already has answers here:
Loop through an array in JavaScript
(46 answers)
Closed 3 years ago.
In an array, it prints out all odd numbers to even numbers, not changing even numbers.
For example, [1, 2, 3, 4] => [2, 2, 6, 4]
var result = '';
var i = 0;
if(array[i]%2 === 1) {
result = array[i]*2;
}
This code prints out only odd number, excluding even numbers in an array.
For example, [1, 2, 3] => [2]

Based on the given example:
[1, 2, 3, 4] => [2, 2, 6, 4]
I take it that every odd number has to be doubled.
Based on that assumption, here is the code:
for (let i = 0; i < array.length; i++)
if (array[i] % 2 !== 0)
array[i] *= 2;
console.log(array);

try this:
var arr = [1, 2, 3, 4]
for (var i = 0; i < arr.length; i++) {
if(arr[i]%2 != 0) {
arr[i] = arr[i]*2;
}
}
console.log(arr);

You need to push even numbers as well.
var array = [1, 2, 3, 4],
result = [],
i = 0;
for (i = 0; i < array.length; i++) {
if (array[i] % 2 === 1) {
result.push(array[i] * 2);
} else {
result.push(array[i]);
}
}
console.log(result);
A shorter approach
var array = [1, 2, 3, 4],
result = array.map(v => v % 2 ? 2 * v : v);
console.log(result);

you can use bitwise & also to check even or odd, lil faster if you have large arrays.
let out = [1, 2, 3, 4].map(e => e & 1 ? e * 2 : e);
console.log(out)

In the loop, check if the item is odd (% returns something other than 0). If it's odd push it's double, if not push the original number:
var array = [1, 2, 3, 4]
var result = []
for(var i = 0; i < array.length; i++) {
result.push(array[i] % 2 ? array[i] * 2 : array[i])
}
console.log(result)
You can also use Array.map():
const array = [1, 2, 3, 4]
const result = array.map(n => n * (n % 2 + 1))
console.log(result)

var array = [1, 2, 3, 4]
var result = [];
var i = 0;
for (var j = 0; j < array.length; j++) {
if(array[j]%2 === 1) {
result.push(array[j]*2);
} else {
result.push(array[j])
}
}
console.log(result)

Related

A function that returns a new array, the values ​of this array must not be repeated more than n times

A task:
Write a function that takes an array and a number n. Then output an array in which there are no elements that are repeated more than n times.
Example:
Input:
n = 3;
arr = [1, 2, 4, 4, 4, 2, 2, 2, 2]
Output:
result = [1, 2, 4, 4, 4, 2, 2]
Tried to do something like that, but it's not working correctly.
let arr = [1, 2, 4, 4, 4, 2, 2, 2, 2];
let new_set = [...new Set(arr)];
let result = [];
console.log(new_set); // [1, 2, 4]
first:
for (let i = 0; i < arr.length; i++) {
if (arr[i] === arr[i - 1]) {
continue first;
}
else {
let count = 0;
for (let j = i; j < arr.length; j++) {
if ((arr[i] === arr[j]) && (count < 3)) {
result.push(arr[j]);
}
}
}
}
You need a persistent outer variable that keeps track of how many times an item has been iterated over so far. Once past the limit, don't push the item being iterated over to the result.
const arr = [1, 2, 4, 4, 4, 2, 2, 2, 2]
let n = 3;
const counts = {};
const result = [];
for (const item of arr) {
counts[item] = (counts[item] || 0) + 1;
if (counts[item] <= n) {
result.push(item);
}
}
console.log(result);
Another option, if you want to use Array.reduce.
It's not as optimised as #CertainPerformance as it uses a filter inside a loop. But for small arrays like this unlikely to make much difference.
const arr = [1, 2, 4, 4, 4, 2, 2, 2, 2]
let n = 3;
const result = arr.reduce((a,v)=>(
a.filter(f=>f===v).length < n ?a.push(v):a,a),[]);
console.log(result);
Code golf version using reduce and without array.filter:
const f=(n,a)=>a.reduce((({c={},r=[]},i)=>
(c[i]??=0,++c[i]>n?0:r.push(i),{c,r})),{}).r;
console.log(f(3, [1, 2, 4, 4, 4, 2, 2, 2, 2]).join());

How to calculate the difference between of the elements in an array starting from the last up to the first in JavaScript?

This is an array given:
arrayNum = [1, 2, 4, 5, 8, 9];
arrayS = [];
for(var i=1, len = array1.length; i<len; i++){
arrayS.push(arrayNum[i]-arrayNum[i-1]);
}
console.log(arrayS);
This code calculates the difference between each two consecutive elements!
However I need to calculate the difference between elements starting from the last up to the first element what would be in this particular case 9-8-5-4-2-1 = -11?!
s1=0;
for(var j=array1[array1.length-1]; j>0; j--){
s1 = s1 - array1[j];
}
console.log(s1);
However this is not working!
In your original solution, you should iterate the index, rather than the element
const arrayNum = [1, 2, 4, 5, 8, 9];
s1 = arrayNum[arrayNum.length - 1];
for (var j = arrayNum.length - 2; j >= 0; j--) {
s1 = s1 - arrayNum[j];
}
console.log(s1);
Or you could use reduce
const arrayNum = [1, 2, 4, 5, 8, 9];
const res = arrayNum.reduce(
(acc, el, index) => acc + (index !== arrayNum.length - 1 ? -1 : 1) * el,
0
);
console.log(res);
You can use Array.reduceRight() to calculate the difference from the end of the array.
Note: that reduce/reduceRight would throw an error when reducing an empty array without an initial value. I use a ternary to check the length, and if it's empty return NaN.
const fn = arr =>
arr.length ?
arrayNum.reduceRight((s, n) => s - n) // if array is not empty
:
NaN // if array is empty
const arrayNum = [1, 2, 4, 5, 8, 9];
const result = arrayNum.reduceRight((s, n) => s - n)
console.log(result);
For the for loop to work, you need to initialize s1 without setting a value, and j with the last index. When calculating s1 check if it's undefined, and initialize it with the current number. If it's not, subtract the current number:
const array1 = [1, 2, 4, 5, 8, 9];
let s1;
for (let j = array1.length - 1; j >= 0; j--) {
s1 = s1 === undefined ? array1[j] : s1 - array1[j];
}
console.log(s1);
Expression 9-8-5-4-2-1 is equal to -(-9+8+5+4+2+1).
-9+8+5+4+2+1 is equal to (-(9*2) + (9+8+5+4+2+1)).
const arrayNum = [1, 2, 4, 5, 8, 9];
const res = -arrayNum.reduce((acc, num) => acc + num
, -arrayNum[arrayNum.length - 1] * 2)
console.log(res)
Issue is with var j=array1[array1.length-1];, not correct index to start with in for-loop.
Try the while loop, should simplify for this case.
array1 = [1, 2, 4, 5, 8, 9];
s1 = array1[array1.length-1];
j = array1.length-1;
while (--j >= 0) s1 -= array1[j];
console.log(s1);

Given an array write a function that returns all the possible triplets/sequences of that array? JavaScript

For example, given A = [1, 2, 1, 1], the function should return 3.
Creates only three different sequences: (1, 2, 1), (1, 1, 1) and (2, 1, 1). The correct answer for this example is 3.
Given A = [1, 2, 3, 4], the function should return 4. There are four
ways: (1, 2, 3), (1, 2, 4), (1, 3, 4) and (2, 3, 4).
Given A = [2, 2, 2, 2], the function should return 1. There is only
one way: (2, 2, 2).
Given A = [2, 2, 1, 2, 2], the function should return 4. There are
four ways: (1, 2, 2), (2, 1, 2), (2, 2, 1) and (2, 2, 2).
Given A = [1, 2], the function should return 0
Write an efficient algorithm for the following assumptions:
N is an integer within the range [0..100,000]; each element of array A
is an integer within the range [1..N].
Here is my Brute Force Solution below!
I was wondering if anybody out there has a better more optimized solution?
Detected time complexity of this solution:
O(N**3*log(N)) or O(N**4)
const theatreTickets = (array) => {
let combos = []
if(array.length < 2) {
combos.length = 0
}
for(let i = 0; i <= array.length; i++) {
for(let j = i + 1; j <= array.length - 1; j++) {
for(let k = j + 1; k <= array.length - 1; k++) {
combos.push([array[i], array[j], array[k]])
}
}
}
combos = Array.from(new Set(combos.map(JSON.stringify)), JSON.parse)
return combos.length
}
console.log(theatreTickets([1, 2, 1, 1])) // Should Be 3
Thank you!
I think you need to combine, algorithm of combination and unique. It will work. Sample is given below.
Source: Efficient algorithm to get the combinations of all items in object
function combine(items, numSubItems) {
var result = [];
var indexes = new Array(numSubItems);
for (var i = 0 ; i < numSubItems; i++) {
indexes[i] = i;
}
while (indexes[0] < (items.length - numSubItems + 1)) {
var v = [];
for (var i = 0 ; i < numSubItems; i++) {
v.push(items[indexes[i]]);
}
result.push(v);
indexes[numSubItems - 1]++;
var l = numSubItems - 1; // reference always is the last position at beginning
while ( (indexes[numSubItems - 1] >= items.length) && (indexes[0] < items.length - numSubItems + 1)) {
l--; // the last position is reached
indexes[l]++;
for (var i = l +1 ; i < numSubItems; i++) {
indexes[i] = indexes[l] + (i - l);
}
}
}
return result;
}
var combinations = combine([1,2,1,1], 3);
console.log([...new Set(combinations.map(x => x.join(",")))]);
combinations = combine([1,2,3,4], 3);
console.log([...new Set(combinations.map(x => x.join(",")))]);

Make average of values inside array to smooth graph line

I have an array which represents the points of a graph with different values like the following one:
var array = [5, 3, 4, 1, 2];
I would like to loop through it and create a new array where the new values are:
An average between the value preceding it and the one coming after it.
Placed among the existing ones.
This means that array[0] will remain at the same position, while the other values will be pushed of one position. The new array should look like this:
var newArray = [5, 4, 3, 3.5, 4, 2.5, 1, 1.5, 2];
Do you have an idea on how to achieve this? Thanks in advance to your replies!
var array = [5, 3, 4, 1, 2];
var newArr = [array[0]]; // start the array with the first from the original
array.reduce((a, b) => {
newArr.push((a + b) / 2, b);
return b;
});
console.log(newArr);
var array = [5, 3, 4, 1, 2];
var newArray = [];
newArray.push(array[0]);
for(var i=0; i < array.length-1; i++)
{
var first = array[i];
var second = array[i+1];
var avg = (first+second)/2;
newArray.push(avg);
newArray.push(second);
}
https://jsfiddle.net/5utkvge8/
You are going to want to loop through your original array, pushing each number to the new one, and if you are not on the final element, get the average of array[i] and array[i+1]
var array = [5, 3, 4, 1, 2];
var newArray = [];
for (var i = 0; i < array.length; i++)
{
newArray.push(array[i])
if (!isNaN(array[i+1]))
{
newArray.push((array[i] + array[i+1]) / 2)
}
}
or in a functional, no-side effects, way:
var array = [5, 3, 4, 1, 2];
var newArray = array.reduce((result, value, index, array) => result.concat(index > 0 && index < array.length ? [(array[index-1] + value)/2, value] : value), [])
In case you can modify the original array:
var array = [5, 3, 4, 1, 2],
len = array.length * 2 - 2;
for (var i = 1; i < len; i = i + 2) {
array.splice(i, null, (array[i-1] + array[i]) / 2);
}
console.log(array);
let createdArr = []
[5, 3, 4, 1, 2].forEach( (item,index,arr) => {
createdArr.push(item)
if( index !== 0 && index + 1 !== arr.length ){
createdArr.push( (item + arr[ index + 1]) / 2 )
}
} )

How to output the number of occurrences in array using JavaScript [duplicate]

This question already has answers here:
How to find the indexes of all occurrences of an element in array?
(16 answers)
Closed 7 years ago.
The goal here is to is count the number of occurrences in the following array:
[2, 3, 7, 9, 7, 3, 2]
For example if the user enters 7, the output should be [2, 4] because 7 occurs at both these indices. What I have so far looks like this
var arr1 = [2,3,7,9,7,3,2];
printArray(arr1);
var indexOfNum = findValueInArray(arr1, num);
if (indexOfNum === -1) {
console.log('%d was not found in the array of random integers.', num);
}
else {
console.log('%d was found in the array of random integers at index %d',num, indexOfNum);
}
My results are:
arr[0] = 2
arr[1] = 3
arr[2] = 7
arr[3] = 9
arr[4] = 7
arr[5] = 3
arr[6] = 2
7 was found in the array of random integers at index 2
I know I'm close but I'm not sure exactly what I'm overlooking. Thank you guys!
try this,
var arr1 = [2,3,7,9,7,3,2];
function occurance(array,element){
var counts = [];
for (i = 0; i < array.length; i++){
if (array[i] === element) {
counts.push(i);
}
}
return counts;
}
occurance(arr1, 2); //returns [0,6]
occurance(arr1, 7); //returns [2,4]
function findValueInArray(arr, num) {
var r = [];
for(i = 0; i < arr.length; i++) (arr[i] == num) ? r.push(i) : '';
return r;
}
function printArray(num, indexOfNum) {
console.log('%d was found ... index %s', num, indexOfNum.join(', '));
}
var arr = [2,3,7,9,7,3,2];
var num = 7;
var indexOfNum = findValueInArray(arr, num);
printArray(num, indexOfNum);
You can do it like this:
var arr = [2, 3, 7, 9, 7, 3, 2];
function occurrences(x, a) {
var pos = [];
a.forEach(function(val, i) {
if (x === a[i]) {
pos.push(i);
}
});
return pos;
}
console.log(occurrences(7, arr)); // [2, 4]
console.log(occurrences(5, arr)); // []
console.log(occurrences(2, arr)); // [0, 6]

Categories