compute how many times the elements appear in the array [duplicate] - javascript

This question already has answers here:
How to count certain elements in array?
(27 answers)
Closed 4 years ago.
input: arbitrary array
output: unique elements and their count
So far I was able to find the unique elements but I can't figure it out how to correlate them with the count for each element. Any suggestions(without using functions if possible - just started and didn't get to functions yet)?
var arr = [3, 4, 4, 3, 3];
var new_arr = [];
for (i = 0; i < arr.length; i++) {
if (new_arr.includes(arr[i])) {
// pass
} else {
new_arr.push(arr[i]);
}
}
console.log(new_arr);

Use an Object instead of an Array to keep track of the count. The key is the number in question and its value is the count.
Use Array#reduce
const res = [3, 4, 4, 3, 3].reduce((acc,cur)=>{
if(acc[cur]) acc[cur]++;
else acc[cur] = 1;
return acc;
}, {});
console.log(res);
Or without any methods:
var arr = [3, 4, 4, 3, 3];
var new_arr = {};
for (i = 0; i < arr.length; i++) {
if (new_arr[arr[i]]) {
new_arr[arr[i]]++;
} else {
new_arr[arr[i]] = 1;
}
}
console.log(new_arr);

Related

How do I filter all items that occur once into one list and all items that occur multiple times into a different one?

I'm currently working on a project but I'm stuck with removing all the duplicates.
I need to remove all the duplicate names and put into a separate file
This is an example of what Im trying to achieve:
So I have an array of numbers (1,2,2,3,3,4,5) and I would like to remove all of the duplicates from the array to result in (1,4,5).
For loop the array and place each value into a hash map that tracks the number of times that number is recorded. Then loop through your hash map and create a new array with only the values that have a record of 1.
const arr = [1, 2, 2, 3, 3, 4, 5];
function removeDuplicates(arr) {
var hashMap = {};
for(let i of arr) {
if(hashMap[i]){
hashMap[i] += 1
} else {
hashMap[i] = 1
}
}
var newArray = [];
for(let [key, value] of Object.entries(hashMap)){
if(value === 1) {
newArray.push(parseInt(key));
} else {
// If you want to do something with values recorded more
// than once, you can do that here.
}
}
return newArray;
}
Without using any external libraries - I am sure there are more concise ways to do it, but this should work:
var numbers = [1, 2, 2, 3, 3, 4, 5];
function removeDuplicates(array) {
var existingValues = []; // Holds all values that exist at least once
var duplicates = []; // Holds all values that are duplicates
array.forEach(function(num) {
if (existingValues.indexOf(num) === -1) {
existingValues.push(num);
} else {
duplicates.push(num);
}
});
// Filter out the values from existingValues that are in the duplicates array
return existingValues.filter(function(i) {
return duplicates.indexOf(i) === -1;
});
}
console.log(removeDuplicates(numbers)); // [1,4,5]
Will the array always be sorted?
no , but that might be something to consider #Thomas
OK, this would have allowed for something like this:
Just looking at the neighbors to determine wether a value is single or has multiple occurances.
const array = [1,2,2,3,3,4,5];
const single = [];
const multiple = [];
for (let i = 0, length = array.length; i < length; ++i) {
let value = array[i];
const isDupe = i > 0 && value === array[i - 1]
|| i + 1 < length && value === array[i + 1];
if (isDupe) {
multiple.push(value);
} else {
single.push(value);
}
}
console.log("singles", single);
console.log("multiple", multiple);
If the data ain't guaranteed to be sorted we need to do a count pass first the check which items are unique in that array and which ones are not. And in a secnd pass we can add them to the result arrays.
const array = [3, 2, 4, 2, 5, 1, 3];
const single = [];
const multiple = [];
const count = {};
for (let i = 0; i<array.length; ++i) {
let value = array[i];
count[value] = (count[value] || 0) + 1;
}
for (let i = 0; i<array.length; ++i) {
let value = array[i];
if (count[value] > 1) {
multiple.push(value);
} else {
single.push(value);
}
}
console.log("singles", single);
console.log("multiple", multiple);
Based on the input you gave: [1, 2, 2, 3, 3, 4, 5] and the fact you said you wanted two outputs: one with the unique values, [1,4,5], and one with duplicates [2,2,3,3].
The below function will give you two arrays as outputs, one with the unique values, and one with the duplicates.
const getUniqueAndDuplicates = (arr) =>{
//use a JavaScript object as a map to count frequency
const map={};
for(let i=0;i<arr.length;i++){
if(map[arr[i]]){map[arr[i]]++;}
else{map[arr[i]]=1;}
}
const uniqueArray=[];
const duplicateArray=[];
for(let key in map){
//get the frequency count
let freq=map[key];
if(freq===1){uniqueArray.push(key);}
else{
for(let i=0;i<freq;i++){
duplicateArray.push(key);
}
}
}
return [uniqueArray,duplicateArray];
}
There's many ways to remove duplication in array. Here's some samples.
Using Set()
Set objects are collections of values. You can iterate through the
elements of a set in insertion order. A value in the Set may only
occur once
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
const duplicated = [1,2,3,2,3,4,3,5];
const uniqSet = new Set(duplicated);
console.log([...uniqSet]) // Should be [1, 2, 3, 4, 5]
Using lodash uniq() method
Document: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
const _ = require('lodash');
const duplicated = [1,2,3,2,3,4,3,5];
const uniq = _.uniq(duplicated);
console.log(uniq) // Should be [1, 2, 3, 4, 5]
Scratch
const duplicated = [1,2,3,2,3,4,3,5];
const uniq = [];
for (const e of duplicated) {
if (!uniq.includes(e)) {
uniq.push(e)
}
}
console.log(uniq) // Should be [1,2,3,4,5]

What is another way to reverse an array without modifying the original and using .reverse()? [duplicate]

This question already has answers here:
Reverse array in Javascript without mutating original array
(15 answers)
Closed 2 years ago.
I have been participating in some javaScript challenges and solved the reverse array challenge without modifying the original using the spread operator. I enjoy solving problems in different ways so i'm curious to find out from you. In what other way would you have solved it or would you solve it (excluding high order functions like map etc) ?
var newArray = [1,2,3,4,5,6];
const reverseArray = () => {
let arr = [...newArray];
for(let i = 0; i <= arr.length; i++){
arr.pop(i)
arr.unshift(i);
}
return arr
}
console.log(reverseArray())
You can use reverse();
var newArray = [1, 2, 3, 4, 5, 6];
var reverse = newArray.reverse();
console.log(reverse)
Use a for loop with increment to set index and then decrement value and push into array
var myArray = [1, 2, 3, 4, 5, 6, 7, 8];
function reverseArray(myArray) { // create a function and pass our array into it
var newArray = []; // define an empty array
for (var i = myArray.length - 1; i >= 0; i--) { // set for loop, declare a decrement for index as i - 1 to adjust for index, if greater than or equal to 0, decrement i
newArray.push(myArray[i]); // push the value into newArray
}
return newArray; // return newArray
}
console.log(reverseArray(myArray));
Use slice() reverse() and map() together index and value through function.
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var div = document.getElementById('div')
function sliceMap() {
reverseArray = myArray.slice(0).reverse().map(
function(value) {
return value;
}
);
div.innerHTML = reverseArray;
}
console.log(sliceMap())
<div id="div"></div>
Mapping values and then using unshift to reverse them.
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var reverseArray = [];
myArray.map((value) => {
reverseArray.unshift(value);
});
console.log(reverseArray)

Fastest way to check if number is in array? [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 2 years ago.
I have to create a function that checks if number is in array. So I've tried this:
function getNumber(x, array) {
for (let i = 0; i < array.length; i++) {
if (!x == array[i]) {
console.log(false);
} else if (x == array[i]) {
console.log(true);
}
}
getNumber(4, [5, 10, 2, 3, 5]);
It works just if x is in array but if it's not console doesn't show anything
I want to know if there is easier(faster) way to check it
I think you can try with .includes() - that's definitely easier:
const array = [5, 10, 2, 3, 5];
const check1 = 4;
const check2 = 10;
const getNumber = (check, array) => {
return array.includes(check);
}
console.log(getNumber(check1, array));
console.log(getNumber(check2, array));
I hope this helps!
Use includes
var arr = [5, 10, 2, 3, 5];
if(arr.includes(21)){
console.log(true);
}else{
console.log(false);
}
You could also use indexOf
const array = [5, 10, 2, 3, 5];
const check1 = 4;
const check2 = 10;
const getNumber = (check, array) => {
return array.indexOf(check)>-1;
}
console.log(getNumber(check1, array));
console.log(getNumber(check2, array));
Might be useful if you need higher browser coverage than includes https://caniuse.com/array-includes

How to change all but one value in an array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Suppose I have an array called array
var array = [0, 1, 2, 3, 4];
Now if I want to change a value in array I could do something like
array[0] = 'zero';
But how do I change 'every' value in array EXCEPT for a particular one?
Basically I am looking for a shorthand for this
array[0] = 9;
array[1] = 9;
array[2] = 9;
//array[3] left untouched
array[4] = 9;
Something like
array[all except 4] = 9;
How can this be easily done with javascript?
You can use .map, testing whether the index is 4, and returning either the value at that index, or your chosen new value:
const array = [
0,
1,
2,
3,
4
];
const array2 = array.map((val, i) => i === 3 ? val : 9);
console.log(array2);
If you need to mutate the original array (which usually isn't a great idea), .map won't work because it creates a new array, but you can forEach and reassign:
const array = [
0,
1,
2,
3,
4
];
array.forEach((val, i) => {
if (i !== 3) array[i] = 9;
});
console.log(array);
You can use map() to transform the array:
var array = [0,1,2,3,4];
array = array.map((el, i) => {
if(i != 3) el = 9;
return el;
});
console.log(array);
You can modify the existing array using .forEach() with an if condition inside:
let array = [0, 1, 2, 3, 4],
indexToSkip = 3;
array.forEach((_, i) => {
if(i !== indexToSkip)
array[i] = 9;
});
console.log(array);
you could do a for loop as follows:
for(i=0; i<array.length; i++){
if(i!='insert number in array you dont want to chage'){
some code..
}
}
Using a simple for loop,
var array = [0, 1, 2, 3, 4];
console.log(array)
var ignore = 3;
var replace = 5;
for (var i = 0; i < array.length; i++) {
if (i !== ignore) {
array[i] = replace;
}
}
console.log(array)
You could use Array#fill and save the value ath the given index and restore this value.
This approach mutates the given array, as wanted.
const fill = (array, all, save) => (value => (array.fill(all)[save] = value, array))(array[save]);
var array = [0, 1, 2, 3, 4];
console.log(array);
fill(array, 9, 3);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Reverse function in JavaScript [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 6 years ago.
Improve this question
I want to get the reverse of this array, in this case ([4,3,2,1]). The problem is I can use no reverse or other shorcuts.
const ar = [1, 2, 3, 4]
const reverse = function (arr) {
let x = arr;
for(i=0; i<x.length;i++) {
x[x.length-i-1]=x[i];
}
return x;
};
const reversedArray = reverse(ar);
console.log(reversedArray);
I thought it must be working, however when I run I get [ 1, 2, 2, 1 ]
as an output. Which is because when i=1 at the second index there is no longer 3. What can I do?
It's like swapping two variables without using a temp variable
const ar = [1, 2, 3, 4]
const reverse = function (arr) {
let x = arr, len = x.length-1;
for(i=0; i<x.length/2;i++) {
x[i]+=x[len-i];
x[len-i]=x[i]-x[len-i];
x[i]-=x[len-i]
}
return x;
};
const reversedArray = reverse(ar);
console.log(reversedArray);
Here is a simple example. But you can achieve the same result with other methods.
function reverse(array){
var new_array = [];
for(var i = 0; i< array.length; i++){
new_array[i] = array[array.length -i - 1];
}
return new_array;
}
//how to use
reverse([1,2,3,4,5]); //output
You can keep it simple by using a regular for loop, and then just unshifting the values onto a new array:
function reverse(arr) {
let reversed = [];
for (let i = 0; i < arr.length; i++) {
reversed.unshift(arr[i]);
}
return reversed;
}
console.log(reverse([1, 2, 3, 4]));
console.log(reverse([6, 7, 8, 9]));
With a while loop and starting from the end of the array :
var arr = [1, 2, 3, 4];
function arrReverse(arr) {
var res = [];
var max = arr.length - 1;
while (max > -1) {
res.push(arr[max]);
max -= 1;
}
return res;
}
var res = arrReverse(arr);
console.log(res);
You're changing the array while you do that because of Javascript's references.
You can use array.prototype.reverse (which is used as [].reverse())
Or you should set a new array and return it.
Don't use the array as a constant. It is probably not letting you make changes in the array.
Then use the reverse method:
ar.reverse();

Categories