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

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]

Related

undefined on running sum challenge [duplicate]

This question already has answers here:
Creating an array of cumulative sum in javascript
(28 answers)
Closed 2 years ago.
I am working on a running sum problem and I keep getting an array of undefined for my output. Here is the example of what the output should be like
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
here is the work I have so far:
var runningSum = function(arr) {
const sum = arr.map(n => {
for (let i = 0; i < arr.length; i++) {
if (i === 0) {
n + 0
} else {
n + arr[i - 1]
}
}
})
return sum
};
const arr = [1, 2, 5, 4]
runningSum(arr)
You are missing these 2:
index of the current iterated element, I store as nIndex
temporary variable that store accumulated sum from beginning to that element, I store as temp
Below fix could help you
var runningSum = function(arr) {
const sum = arr.map((n, nIndex) => {
let temp = n
for (let i = 0; i < nIndex + 1; i++) {
if (i === 0) {
temp += 0
} else {
temp += arr[i - 1]
}
}
return temp
})
return sum
}
const arr = [1, 2, 3, 4]
console.log(runningSum(arr))

odd to even numbers in an array javascript [duplicate]

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)

Check array in JS - is list sorted? [duplicate]

This question already has answers here:
Check if an array is descending, ascending or not sorted?
(10 answers)
Check if array values are ascending or descending
(1 answer)
Closed 4 years ago.
I need to create a program that checks the list in the array is sorted. I have three input data:
1,2,3,4,5
1,2,8,9,9
1,2,2,3,2
So here is my code:
let sorts = +gets(); // 3
let list = [];
for (let i = 0; i < sorts; i++) {
list[i] = gets().split(',').map(Number); // The Array will be: [ [ 1, 2, 3, 4, 5 ], [ 1, 2, 8, 9, 9 ], [ 1, 2, 2, 3, 2 ] ]
}
for (let i = 0; i < list[i][i].length; i++){
if (list[i][i] < list[i][i +1]) {
print('true');
} else {
print('false');
}
}
I need to print for all lists on new line true or false. For this example my output needs to be:
true
true
false
I have no idea how to resolve this.
You can use array#every to check if each value is greater than the previous value.
const isSorted = arr => arr.every((v,i,a) => !i || a[i-1] <= v);
console.log(isSorted([1,2,3,4,5]));
console.log(isSorted([1,2,8,9,9]));
console.log(isSorted([1,2,2,3,2]));
How about something like this:
!![1,2,3,4,5].reduce((n, item) => n !== false && item >= n && item)
// true
!![1,2,8,9,9].reduce((n, item) => n !== false && item >= n && item)
// true
!![1,2,2,3,2].reduce((n, item) => n !== false && item >= n && item)
// false
Reduce will literally reduce the array down to a single value - a boolean in our case.
Here, we are calling a function per iteration, the (n, item) is our function signature, it's body being n !== false && item >- n && item - we are making sure that n exists (n is our accumulator - read up!), testing if item is greater than n, and making sure item exists.
This happens for every element in your array. We then use !! to force the result into a tru boolean.
Simply try this way by using slice method : It will check if previous element is less than the next element.If the condition is true for every element then it will return true else false
arr.slice(1).every((item, i) => arr[i] <= item);
Checkout this below sample as Demo
var arr = [[1,2,3,4,5],[1,2,8,9,9],[1,2,2,3,2],[0,1,2,3,4,5]];
function isArrayIsSorted (arr) {
return arr.slice(1).every((item, i) => arr[i] <= item)
}
var result= [];
for (var i = 0; i < arr.length; i++){
result.push(isArrayIsSorted(arr[i]))
}
console.log(result);
Sorted Number Lists
Including Negative Numbers, Zeros, and Adjacent Duplicates
Use every() method which will return true should all of the numbers be in order otherwise it will return false. The conditions are as follows:
(num <= arr[idx + 1]) || (idx === arr.length - 1)
if the current number is less than or equal to the next number...
OR...
if the current index is equal to the last index...
return 1 (truthy)
Demo
var arr0 = [1, 2, 3, 4, 5];
var arr1 = [1, 2, 8, 9, 9];
var arr2 = [1, 2, 2, 3, 2];
var arr3 = [0, 0, 0, 1, 3];
var arr4 = [-3, 0, 1, 3, 3];
var arr5 = [-4, -2, 0, 0, -4];
function sorted(array) {
return array.every(function(num, idx, arr) {
return (num <= arr[idx + 1]) || (idx === arr.length - 1) ? 1 : 0;
});
}
console.log(arr0 +' | '+sorted(arr0));
console.log(arr1 +' | '+sorted(arr1));
console.log(arr2 +' | '+sorted(arr2));
console.log(arr3 +' | '+sorted(arr3));
console.log(arr4 +' | '+sorted(arr4));
console.log(arr5 +' | '+sorted(arr5));
var str = ["1,2,3,4,5", "1,2,8,9,9", "1,2,2,3,2"];
for (var i in str){
var list = str[i].split(',').map(Number);
console.log(list);
var isSorted = true;
for(var j = 0 ; j < list.length - 1 ; j++){
if(list[j] > list[j+1]) {
isSorted = false;
break;
}
}
console.log(isSorted);
}
Maybe you can use this helping method that checks if is sorted correctly:
var arr1 = [1, 2, 3, 4, 4];
var arr2 = [3, 2, 1];
console.log(checkList(arr1));
console.log(checkList(arr2));
function checkList(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i + 1]) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
}
return true;
}
There are plenty of ways how to do that. Here is mine
const isArraySorted = array =>
array
.slice(0) // clone array
.sort((a, b) => a - b) // sort it
.every((el, i) => el === array[i]) // compare with initial value)
You can check if stringified sorted copy of original array has same value as the original one. Might not be the most cool or performant one, but I like it's simplicity and clarity.
const arraysToCheck = [
[1, 2, 3, 4, 5],
[1, 2, 8, 9, 9],
[1, 2, 2, 3, 2]
]
const isSorted = arraysToCheck.map(
item => JSON.stringify([...item].sort((a, b) => a - b)) === JSON.stringify(item)
);
console.log(isSorted);
If i get what you mean, you want to know if an array is sorted or not. This is an example of such a solution, try it. I pasted some codes below.
var myArray=[1,4,3,6];
if(isSorted(myArray)){
console.log("List is sorted");
}else{
console.log("List is not sorted");
}
function isSorted(X){
var sorted=false;
for(var i=0;i<X.length;i++){
var next=i+1;
if (next<=X.length-1){
if(X[i]>X[next]){
sorted=false;
break;
}else{
sorted=true;
}
}
}
return sorted;
}

finding all missing elements in an array/range javascript

I am trying to to write a function to find all missing elements in an array. The series goes from 1...n. the input is an unsorted array and the output is the missing numbers.
below is what I have so far:
function findMissingElements(arr) {
arr = arr.sort();
var missing = [];
if (arr[0] !== 1) {
missing.unshift(1);
}
// Find the missing array items
for (var i = 0; i < arr.length; i++) {
if ((arr[i + 1] - arr[i]) > 1) {
missing.push(arr[i + 1] - 1);
}
}
return missing;
}
var numbers = [1, 3, 4, 5, 7, 8]; // Missing 2,6
var numbers2 = [5, 2, 3]; //missing 1, 4
var numbers3 = [1, 3, 4, 5, 7]; // Missing 2,6
console.log(findMissingElements(numbers)); // returns 2,6 correct
console.log(findMissingElements(numbers2)); // returns 1,4
console.log(findMissingElements(numbers3)); // returns 2, 6
I "manually" checked for the first element with an if block, is there any way to handle the case of the first element inside the for loop?
You can produce that by tracking which number should appear next and adding it to a list of missing numbers while it is less than the next number.
function findMissingElements(arr) {
// Make sure the numbers are in order
arr = arr.slice(0).sort(function(a, b) { return a - b; });
let next = 1; // The next number in the sequence
let missing = [];
for (let i = 0; i < arr.length; i++) {
// While the expected element is less than
// the current element
while (next < arr[i]) {
// Add it to the missing list and
// increment to the next expected number
missing.push(next);
next++;
}
next++;
}
return missing;
}
A not so efficient but more intuitive solution:
var n = Math.max.apply(null, arr); // get the maximum
var result = [];
for (var i=1 ; i<n ; i++) {
if (arr.indexOf(i) < 0) result.push(i)
}
Aside from the fact that your tests are not consistent, this feels a bit neater to me:
function findMissingElements (arr, fromFirstElement) {
arr.sort();
var missing = [];
var next = fromFirstElement ? arr[0] : 1;
while(arr.length) {
var n = arr.shift();
while (n != next) {
missing.push(next++);
}
next++;
}
return missing;
}
var numbers = [1, 3, 4, 5, 7, 8]; // Missing 2,6
var numbers2 = [5, 2, 3]; // Missing 1, 4
var numbers3 = [1, 3, 4, 5, 7]; // Missing 2, 6
console.log(findMissingElements(numbers)); // returns 2, 6
console.log(findMissingElements(numbers2)); // returns 1, 4
console.log(findMissingElements(numbers3)); // returns 2, 6
I've added an argument fromFirstElement which, if passed true, will enable you to start from a number defined by the first element in the array you pass.

Convert a 1D array to 2D array [duplicate]

This question already has answers here:
Convert simple array into two-dimensional array (matrix)
(19 answers)
Closed 8 years ago.
I am working on a program where I have to read the values from a textfile into an 1D array.I have been succesfull in getting the numbers in that 1D array.
m1=[1,2,3,4,5,6,7,8,9]
but I want the array to be
m1=[[1,2,3],[4,5,6],[7,8,9]]
You can use this code :
const arr = [1,2,3,4,5,6,7,8,9];
const newArr = [];
while(arr.length) newArr.push(arr.splice(0,3));
console.log(newArr);
http://jsfiddle.net/JbL3p/
Array.prototype.reshape = function(rows, cols) {
var copy = this.slice(0); // Copy all elements.
this.length = 0; // Clear out existing array.
for (var r = 0; r < rows; r++) {
var row = [];
for (var c = 0; c < cols; c++) {
var i = r * cols + c;
if (i < copy.length) {
row.push(copy[i]);
}
}
this.push(row);
}
};
m1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
m1.reshape(3, 3); // Reshape array in-place.
console.log(m1);
.as-console-wrapper { top:0; max-height:100% !important; }
Output:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
JSFiddle DEMO
I suppose you could do something like this... Just iterate over the array in chunks.
m1=[1,2,3,4,5,6,7,8,9];
// array = input array
// part = size of the chunk
function splitArray(array, part) {
var tmp = [];
for(var i = 0; i < array.length; i += part) {
tmp.push(array.slice(i, i + part));
}
return tmp;
}
console.log(splitArray(m1, 3)); // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Obviously there is no error checking, but you can easily add that.
DEMO
There are so many ways to do the same thing:
var m = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var n = [];
var i = 0;
for (l = m.length + 1; (i + 3) < l; i += 3) {
n.push(m.slice(i, i + 3));
}
// n will be the new array with the subarrays
The above is just one.

Categories