Related
I have two arrays
var arrayA = ["a", "a", "b", "b", "a", "c"];
var arrayB = [10, 20, 3, 2, 20, 5];
As you can see, arrayA[0], arrayA[1], arrayA[4] have an same elements (arrayA[2], arrayA[3] same too).
So based on above example, I want arrayB[0], arrayB[1], arrayB[4] will be summed up, and arrayB[2], arrayB[3] too.
expectation output
arrayA = ["a", "b", "c"];
arrayB = [50, 5, 5];
It's possible to sum the arrayB elements if arrayA have same elements based arrayA index? and is there an Lodash/Underscore function to do this?
You could use an object for the indices and maintain the values.
var arrayA = ["a", "a", "b", "b", "a", "c"],
arrayB = [10, 20, 3, 2, 20, 5],
indices = Object.create(null),
groupedA = [],
groupedB = [];
arrayA.forEach(function (a, i) {
if (!(a in indices)) {
groupedA.push(a);
indices[a] = groupedB.push(0) - 1;
}
groupedB[indices[a]] += arrayB[i];
});
console.log(groupedA);
console.log(groupedB);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Version which mutates the original arrays.
var arrayA = ["a", "a", "b", "b", "a", "c"],
arrayB = [10, 20, 3, 2, 20, 5],
indices = Object.create(null),
i = 0;
while (i < arrayA.length) {
if (!(arrayA[i] in indices)) {
indices[arrayA[i]] = i++;
continue;
}
arrayB[indices[arrayA[i]]] += arrayB.splice(i, 1)[0];
arrayA.splice(i, 1);
}
console.log(arrayA);
console.log(arrayB);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Here's a solution using lodash:
[arrayA, arrayB] = _(arrayA)
.zip(arrayB)
.groupBy(0)
.mapValues( grp => _.sumBy(grp,1))
.thru(obj => [_.keys(obj), _.values(obj)])
.value();
zip will associate each element in arrayA with the corresponding element in arrayB e.g. [ ['a', 10], ['a', 20], ...]
We then groupBy the value in position 0 giving an object something like:
{
a: ['a', 10], ['a', 20], ['a', 20'],
b: ['b', 3] ...,
c: ...
}
The values of each key are then mapped to the sum of the values in position 1 before finally returning the keys and the values in separate arrays.
You can reduce both arrays into an ES6 Map, and then spread the keys for arrayA, and the values for arrayB:
const arrayA = ["a", "a", "b", "b", "a", "c"];
const arrayB = [10, 20, 3, 2, 20, 5];
const map = arrayA.reduce((m, c, i) => m.set(c, (m.get(c) || 0) + arrayB[i]), new Map());
const arrA = [...map.keys()];
const arrB = [...map.values()];
console.log(arrA);
console.log(arrB);
With an intermediary "result" object:
var arrayA = ["a", "a", "b", "b", "a", "c"];
var arrayB = [10, 20, 3, 2, 20, 5];
var result = {};
for (var i = 0, max = arrayA.length; i < max; i++) {
if (!result[arrayA[i]]) {
result[arrayA[i]] = 0;
}
result[arrayA[i]] += arrayB[i];
}
var keys = Object.keys(result);
arrayA = [];
arrayB = [];
for (var i = 0, max = keys.length; i < max; i++) {
arrayA.push(keys[i]);
arrayB.push(result[keys[i]]);
}
You can compute sums of all elements in arrayB that corresponds to each element in arrayA, store these sums in an object and use Object.values to get an array of the sums.
var arrayA = ["a", "a", "b", "b", "a", "c"];
var arrayB = [10, 20, 3, 2, 20, 5];
var sum = {};
arrayA.forEach((l, index) => {
sum[l] = (sum[l] || 0) + arrayB[index];
});
var res = Object.values(sum);
console.log(res);
And it can be done even shorter with array.prototype.reduce:
var arrayA = ["a", "a", "b", "b", "a", "c"];
var arrayB = [10, 20, 3, 2, 20, 5];
var res = Object.values(arrayA.reduce((m, l, index) => {
m[l] = (m[l] || 0) + arrayB[index];
return m;
}, {}));
console.log(res);
let _ = require('underscore');
var arrayA = ["a", "a", "b", "b", "a", "c"];
var arrayB = [10, 20, 3, 2, 20, 5];
let res = {};
_.each(arrayA, (item, key) => {
if (! res[item]) {
res[item] = arrayB[key];
} else {
res[item] = res[item] + arrayB[key];
}
});
arrayA = [];
arrayB = [];
_.each(res,(value,key) => {
arrayA.push(key);
arrayB.push(value);
});
console.log(arrayA);
console.log(arrayB);
First fill the dict and then fill de arrays with the keys and values
let arrayA = ["a", "a", "b", "b", "a", "c"];
let arrayB = [10, 20, 3, 2, 20, 5];
let result = {};
for (let i=0; i < arrayA.length; i++ ){
let valueB = 0;
if (arrayB.length > i) {
valueB = arrayB[i];
}
if (result.hasOwnProperty(arrayA[i])) {
result[arrayA[i]] += valueB;
}
else {
result[arrayA[i]] = valueB;
}
}
let resultA = [];
let resultB = [];
for (let k in result) {
resultA.push(k);
resultB.push(result[k]);
}
console.log(resultA);
console.log(resultB);
Use Array#reduce method.
var arrayA = ["a", "a", "b", "b", "a", "c"];
var arrayB = [10, 20, 3, 2, 20, 5];
// reference to keep the index
var ref = {},
// array for keeping first result
res1 = [];
var res2 = arrayA
// iterate over the first array
.reduce(function(arr, v, i) {
// check index presenet in the refernece object
if (!(v in ref)) {
// if not then define the index and insert 0 in the array(defining the new index)
arr[ref[v] = arr.length] = 0;
// push value into the array( for unique value )
res1.push(v);
}
// update the element at the index
arr[ref[v]] += arrayB[i];
// return the array reference
return arr;
// initialize initial value as an empty array to keep result
}, [])
console.log(res1, res2);
:) I need to return a new object whose properties are those in the given object and whose keys are present in the given array.
code attempt:
var arr = ['a', 'c', 'e'];
var obj = {
a: 1,
b: 2,
c: 3,
d: 4
};
function select(arr, obj) {
var result = {};
var array = [];
for (var key in obj){
array.push(key);
}
var num = arr.length + obj.length;
for (var i = 0; i < num; i++) {
for(var j = 0; j < num; j++) {
if (arr[i] === array[j]) {
result.array[i] = obj.arr[i];
}
}
}
return result;
}
(incorrect) result:
{}
desired result:
// --> { a: 1, c: 3 }
Any advice? Thank you! :)
Longer, but more readable version:
var arr = ['a', 'c', 'e'],
obj = {a:1,b:2,c:3,d:4},
hash = {};
arr.forEach(function(v){ //iterate over each element from arr
Object.keys(obj).some(function(c){ //check if any key from obj is equal to iterated element from arr
if (v == c) {
hash[v] = obj[c]; //if it is equal, make a new key inside hash obj and assign it's value from obj to it
}
});
});
console.log(hash);
Short version:
var arr = ['a', 'c', 'e'],
obj = {a:1,b:2,c:3,d:4},
hash = {};
arr.forEach(v => Object.keys(obj).some(c => v == c ? hash[v] = obj[c] : null));
console.log(hash);
You could iterate the given keys, test if it is a key in the object and assign the value to the same key in the result object.
function select(arr, obj) {
var result = {};
arr.forEach(function (k) {
if (k in obj) {
result[k] = obj[k];
}
});
return result;
}
var arr = ['a', 'c', 'e'],
obj = { a: 1, b: 2, c: 3, d: 4 };
console.log(select(arr, obj));
I'am pretty new to JavaScript and i have this exercise that have been bugging me for a some hours now.
I want to write a Javascript function that expects an array which could contain string and/or numbers (as well as finite levels of nested arrays of strings and/or numbers), and returns a Javascript object which shows the total number of occurences of each unique values.
Something like this
var myArray = [ 1, 2, 1, 'a', [ 'd', 5, 6 ], 'A', 2, 'b', 1, 'd' ];
var myResult = myFunction( myArray );
Then it should return something like this
yourResult = {
1: 3,
2: 2,
'a': 1,
'd': 2,
5: 1,
6: 1,
'A': 1,
'b': 1,
}
So far what i have is this. I dont know how to create the object but this is not working at all. It ads all the values in the array
Array.prototype.contains = function(v) {
for(var i = 0; i < this.length; i++) {
if(this[i] === v) return true;
}
return false;
};
Array.prototype.unique = function() {
var arr = [];
for(var i = 0; i < this.length; i++) {
if(this[i] instanceof Array) {
for(var j = 0; i < this[i].length; j++){
if (!arr.contains(this[i][j])){
arr.push(this[i][j]);
}
}
}
if(!arr.contains(this[i])) {
arr.push(this[i]);
}
}
return arr;
}
var myArray = [1,3,4,2,1,[1,2,3,6],2,3,8];
var myResult = duplicates.unique();
console.log(myResult);
I would seperate it into 2 major problems:
1. Make the array members to be at one level (not nested).
2. Count repeats
The first one I solved with recursion, hope it's meet the requirements. The second is about counting instances..
Hope it's help
Fiddle example
var myArray = [ 1, 2, 1, 'a', [ 'd', 5, 6 ], 'A', 2, 'b', 1, 'd' ];
var myResult = myFunction( myArray );
console.log(myResult);
function myFunction(arr) {
var r = {};
for (var i=0 ; i < arr.length ; i++) {
if( Object.prototype.toString.call( arr[i] ) === '[object Array]' ) {
var sub = myFunction(arr[i]);
for (var attrname in sub) {
if (r[attrname])
r[attrname]++;
else {
r[attrname] = sub[attrname];
r[attrname] = 1;
}
}
}
else if (r[arr[i]])
r[arr[i]]++;
else
r[arr[i]] = 1;
}
return r;
}
An associative array is what you need to hold the result:
var associative_array={}
then you can use a function like this:
function add_to_as(value){ //Add element to the global associative array
if(associative_array[value]==undefined){
associative_array[value]=1;
}
else{
associative_array[value] +=1;//add one
}
}
function myFunction( mydata ){
for(var i = 0; i < mydata.length; i++) {
if(mydata[i] instanceof Array) { //recurse on sublists if any
myFunction(mydata[i])
}
else{
add_to_as(mydata[i]);
}
}
}
//To test the function
var myArray = [ 1, 2, 1, 'a', [ 'd', 5, 6 ], 'A', 2, 'b', 1, 'd' ];
myFunction(myArray);
console.log(associative_array);
Besides your code
you can put all the elements of your array to a second array containing all the elements of array and sub arrays. Then you can iterate over second array and find the occurrence of each element like this
var arr1 = [1, 2, 1, 'a', ['d', 5, 6], 'A', 2, 'b', 1, 'd'];
var arr = [];
var obj = {};
for (var i = 0; i < arr1.length; i++) {
if (arr1[i].length == undefined || arr1[i].length == 1) {
arr.push(arr1[i]);
}
else {
for (var j = 0; j < arr1[i].length; j++) {
arr.push(arr1[i][j]);
}
}
}
for (var i = 0, j = arr.length; i < j; i++) {
if (obj[arr[i]]) {
obj[arr[i]]++;
}
else {
obj[arr[i]] = 1;
}
}
console.log(obj);
DEMO
Updated:In case of nested arrays
var arr2 = [1, 2, 1, 'a', ['d', 5, 6,['d', 5, 6,['d', 5, 6]]], 'A', 2, 'b', 1, 'd'];
var arr = [];
var obj = {};
function singleArray(arr1) {
for (var i = 0; i < arr1.length; i++) {
if (arr1[i].length == undefined || arr1[i].length == 1) {
arr.push(arr1[i]);
}
else {
singleArray(arr1[i]);
}
}
}
singleArray(arr2);
for (var i = 0, j = arr.length; i < j; i++) {
if (obj[arr[i]]) {
obj[arr[i]]++;
}
else {
obj[arr[i]] = 1;
}
}
console.log(obj);
DEMO
Currently, I got an array like that:
var uniqueCount = Array();
After a few steps, my array looks like that:
uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];
How can I count how many a,b,c are there in the array? I want to have a result like:
a = 3
b = 1
c = 2
d = 2
etc.
const counts = {};
const sampleArray = ['a', 'a', 'b', 'c'];
sampleArray.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts)
Something like this:
uniqueCount = ["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
var count = {};
uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});
console.log(count);
Use a simple for loop instead of forEach if you don't want this to break in older browsers.
I stumbled across this (very old) question. Interestingly the most obvious and elegant solution (imho) is missing: Array.prototype.reduce(...). All major browsers support this feature since about 2011 (IE) or even earlier (all others):
var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce(function(prev, cur) {
prev[cur] = (prev[cur] || 0) + 1;
return prev;
}, {});
// map is an associative array mapping the elements to their frequency:
console.log(map);
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
EDIT:
By using the comma operator in an arrow function, we can write it in one single line of code:
var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce((cnt, cur) => (cnt[cur] = cnt[cur] + 1 || 1, cnt), {});
// map is an associative array mapping the elements to their frequency:
console.log(map);
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
However, as this may be harder to read/understand, one should probably stick to the first version.
function count() {
array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
array_elements.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < array_elements.length; i++) {
if (array_elements[i] != current) {
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times<br>');
}
current = array_elements[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times');
}
}
count();
Demo Fiddle
You can use higher-order functions too to do the operation. See this answer
Simple is better, one variable, one function :)
const arr = ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
const counts = arr.reduce((acc, value) => ({
...acc,
[value]: (acc[value] || 0) + 1
}), {});
console.log(counts);
Single line based on reduce array function
const uniqueCount = ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
const distribution = uniqueCount.reduce((acum,cur) => Object.assign(acum,{[cur]: (acum[cur] || 0)+1}),{});
console.log(JSON.stringify(distribution,null,2));
// Initial array
let array = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a'];
// Unique array without duplicates ['a', 'b', ... , 'h']
let unique = [...new Set(array)];
// This array counts duplicates [['a', 3], ['b', 2], ... , ['h', 3]]
let duplicates = unique.map(value => [value, array.filter(str => str === value).length]);
Nobody responding seems to be using the Map() built-in for this, which tends to be my go-to combined with Array.prototype.reduce():
const data = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
const result = data.reduce((a, c) => a.set(c, (a.get(c) || 0) + 1), new Map());
console.log(...result);
N.b., you'll have to polyfill Map() if wanting to use it in older browsers.
I think this is the simplest way how to count occurrences with same value in array.
var a = [true, false, false, false];
a.filter(function(value){
return value === false;
}).length
You can solve it without using any for/while loops ou forEach.
function myCounter(inputWords) {
return inputWords.reduce( (countWords, word) => {
countWords[word] = ++countWords[word] || 1;
return countWords;
}, {});
}
Hope it helps you!
It is simple in javascript using array reduce method:
const arr = ['a','d','r','a','a','f','d'];
const result = arr.reduce((json,val)=>({...json, [val]:(json[val] | 0) + 1}),{});
console.log(result)
//{ a:3,d:2,r:1,f:1 }
You can have an object that contains counts. Walk over the list and increment the count for each element:
var counts = {};
uniqueCount.forEach(function(element) {
counts[element] = (counts[element] || 0) + 1;
});
for (var element in counts) {
console.log(element + ' = ' + counts[element]);
}
// new example.
var str= [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5];
function findOdd(para) {
var count = {};
para.forEach(function(para) {
count[para] = (count[para] || 0) + 1;
});
return count;
}
console.log(findOdd(str));
const obj = {};
const uniqueCount = [ 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a' ];
for (let i of uniqueCount) obj[i] ? obj[i]++ : (obj[i] = 1);
console.log(obj);
You can do something like that:
uniqueCount = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = new Object();
for(var i = 0; i < uniqueCount.length; i++) {
if(map[uniqueCount[i]] != null) {
map[uniqueCount[i]] += 1;
} else {
map[uniqueCount[i]] = 1;
}
}
now you have a map with all characters count
uniqueCount = ["a","b","a","c","b","a","d","b","c","f","g","h","h","h","e","a"];
var count = {};
uniqueCount.forEach((i) => { count[i] = ++count[i]|| 1});
console.log(count);
Duplicates in an array containing alphabets:
var arr = ["a", "b", "a", "z", "e", "a", "b", "f", "d", "f"],
sortedArr = [],
count = 1;
sortedArr = arr.sort();
for (var i = 0; i < sortedArr.length; i = i + count) {
count = 1;
for (var j = i + 1; j < sortedArr.length; j++) {
if (sortedArr[i] === sortedArr[j])
count++;
}
document.write(sortedArr[i] + " = " + count + "<br>");
}
Duplicates in an array containing numbers:
var arr = [2, 1, 3, 2, 8, 9, 1, 3, 1, 1, 1, 2, 24, 25, 67, 10, 54, 2, 1, 9, 8, 1],
sortedArr = [],
count = 1;
sortedArr = arr.sort(function(a, b) {
return a - b
});
for (var i = 0; i < sortedArr.length; i = i + count) {
count = 1;
for (var j = i + 1; j < sortedArr.length; j++) {
if (sortedArr[i] === sortedArr[j])
count++;
}
document.write(sortedArr[i] + " = " + count + "<br>");
}
simplified sheet.js answare
var counts = {};
var aarr=['a','b','a'];
aarr.forEach(x=>counts[x]=(counts[x] || 0)+1 );
console.log(counts)
CODE:
function getUniqueDataCount(objArr, propName) {
var data = [];
if (Array.isArray(propName)) {
propName.forEach(prop => {
objArr.forEach(function(d, index) {
if (d[prop]) {
data.push(d[prop]);
}
});
});
} else {
objArr.forEach(function(d, index) {
if (d[propName]) {
data.push(d[propName]);
}
});
}
var uniqueList = [...new Set(data)];
var dataSet = {};
for (var i = 0; i < uniqueList.length; i++) {
dataSet[uniqueList[i]] = data.filter(x => x == uniqueList[i]).length;
}
return dataSet;
}
Snippet
var data= [
{day:'Friday' , name: 'John' },
{day:'Friday' , name: 'John' },
{day:'Friday' , name: 'Marium' },
{day:'Wednesday', name: 'Stephanie' },
{day:'Monday' , name: 'Chris' },
{day:'Monday' , name: 'Marium' },
];
console.log(getUniqueDataCount(data, ['day','name']));
function getUniqueDataCount(objArr, propName) {
var data = [];
if (Array.isArray(propName)) {
propName.forEach(prop => {
objArr.forEach(function(d, index) {
if (d[prop]) {
data.push(d[prop]);
}
});
});
} else {
objArr.forEach(function(d, index) {
if (d[propName]) {
data.push(d[propName]);
}
});
}
var uniqueList = [...new Set(data)];
var dataSet = {};
for (var i = 0; i < uniqueList.length; i++) {
dataSet[uniqueList[i]] = data.filter(x => x == uniqueList[i]).length;
}
return dataSet;
}
var uniqueCount = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
// here we will collect only unique items from the array
var uniqueChars = [];
// iterate through each item of uniqueCount
for (i of uniqueCount) {
// if this is an item that was not earlier in uniqueCount,
// put it into the uniqueChars array
if (uniqueChars.indexOf(i) == -1) {
uniqueChars.push(i);
}
}
// after iterating through all uniqueCount take each item in uniqueChars
// and compare it with each item in uniqueCount. If this uniqueChars item
// corresponds to an item in uniqueCount, increase letterAccumulator by one.
for (x of uniqueChars) {
let letterAccumulator = 0;
for (i of uniqueCount) {
if (i == x) {letterAccumulator++;}
}
console.log(`${x} = ${letterAccumulator}`);
}
var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var newArr = [];
testArray.forEach((item) => {
newArr[item] = testArray.filter((el) => {
return el === item;
}).length;
})
console.log(newArr);
Using this solution you can now get map of repeated items:
Str= ['a','b','c','d','d','e','a','h','e','a'];
var obj= new Object();
for(var i = 0; i < Str.length; i++) {
if(obj[Str[i]] != null) {
obj[Str[i]] += 1;
} else {
obj[Str[i]] = 1;
}
}
console.log(obj);
Steps : first check if in accumulator has the current value or not if not ,than for that particular value set the count as 1 and in else condition ,if value alreadt exist in accumulator the simple increment the count.
const testarr = [1,2,1,3,1,2,4];
var count = testarr.reduce((acc,currentval)=>{
if(acc[currentval]){ acc[currentval] = ++acc[currentval]; }else{ acc[currentval] = 1; } return acc; },{})
console.log(count);
use forEach() method for convinience
var uniqueCount="a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
var count=0;
var obj={};
uniqueCount.forEach((i,j)=>{
count=0;
var now=i;
uniqueCount.forEach((i,j)=>{
if(now==uniqueCount[j]){
count++;
obj[i]=count;
}
});
});
console.log(obj);
A combination of good answers:
var count = {};
var arr = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a'];
var iterator = function (element) {
count[element] = (count[element] || 0) + 1;
}
if (arr.forEach) {
arr.forEach(function (element) {
iterator(element);
});
} else {
for (var i = 0; i < arr.length; i++) {
iterator(arr[i]);
}
}
Hope it's helpful.
By using array.map we can reduce the loop, see this on jsfiddle
function Check(){
var arr = Array.prototype.slice.call(arguments);
var result = [];
for(i=0; i< arr.length; i++){
var duplicate = 0;
var val = arr[i];
arr.map(function(x){
if(val === x) duplicate++;
})
result.push(duplicate>= 2);
}
return result;
}
To Test:
var test = new Check(1,2,1,4,1);
console.log(test);
var string = ['a','a','b','c','c','c','c','c','a','a','a'];
function stringCompress(string){
var obj = {},str = "";
string.forEach(function(i) {
obj[i] = (obj[i]||0) + 1;
});
for(var key in obj){
str += (key+obj[key]);
}
console.log(obj);
console.log(str);
}stringCompress(string)
/*
Always open to improvement ,please share
*/
Create a file for example demo.js and run it in console with node demo.js and you will get occurrence of elements in the form of matrix.
var multipleDuplicateArr = Array(10).fill(0).map(()=>{return Math.floor(Math.random() * Math.floor(9))});
console.log(multipleDuplicateArr);
var resultArr = Array(Array('KEYS','OCCURRENCE'));
for (var i = 0; i < multipleDuplicateArr.length; i++) {
var flag = true;
for (var j = 0; j < resultArr.length; j++) {
if(resultArr[j][0] == multipleDuplicateArr[i]){
resultArr[j][1] = resultArr[j][1] + 1;
flag = false;
}
}
if(flag){
resultArr.push(Array(multipleDuplicateArr[i],1));
}
}
console.log(resultArr);
You will get result in console as below:
[ 1, 4, 5, 2, 6, 8, 7, 5, 0, 5 ] . // multipleDuplicateArr
[ [ 'KEYS', 'OCCURENCE' ], // resultArr
[ 1, 1 ],
[ 4, 1 ],
[ 5, 3 ],
[ 2, 1 ],
[ 6, 1 ],
[ 8, 1 ],
[ 7, 1 ],
[ 0, 1 ] ]
Quickest way:
Сomputational complexity is O(n).
function howMuchIsRepeated_es5(arr) {
const count = {};
for (let i = 0; i < arr.length; i++) {
const val = arr[i];
if (val in count) {
count[val] = count[val] + 1;
} else {
count[val] = 1;
}
}
for (let key in count) {
console.log("Value " + key + " is repeated " + count[key] + " times");
}
}
howMuchIsRepeated_es5(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);
The shortest code:
Use ES6.
function howMuchIsRepeated_es6(arr) {
// count is [ [valX, count], [valY, count], [valZ, count]... ];
const count = [...new Set(arr)].map(val => [val, arr.join("").split(val).length - 1]);
for (let i = 0; i < count.length; i++) {
console.log(`Value ${count[i][0]} is repeated ${count[i][1]} times`);
}
}
howMuchIsRepeated_es6(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);
var arr = ['a','d','r','a','a','f','d'];
//call function and pass your array, function will return an object with array values as keys and their count as the key values.
duplicatesArr(arr);
function duplicatesArr(arr){
var obj = {}
for(var i = 0; i < arr.length; i++){
obj[arr[i]] = [];
for(var x = 0; x < arr.length; x++){
(arr[i] == arr[x]) ? obj[arr[i]].push(x) : '';
}
obj[arr[i]] = obj[arr[i]].length;
}
console.log(obj);
return obj;
}
I have two arrays:
var array1 = ["A", "B", "C"];
var array2 = ["1", "2", "3"];
How can I set another array to contain every combination of the above, so that:
var combos = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"];
Or if you'd like to create combinations with an arbitrary number of arrays of arbitrary sizes...(I'm sure you can do this recursively, but since this isn't a job interview, I'm instead using an iterative "odometer" for this...it increments a "number" with each digit a "base-n" digit based on the length of each array)...for example...
combineArrays([ ["A","B","C"],
["+", "-", "*", "/"],
["1","2"] ] )
...returns...
[
"A+1","A+2","A-1", "A-2",
"A*1", "A*2", "A/1", "A/2",
"B+1","B+2","B-1", "B-2",
"B*1", "B*2", "B/1", "B/2",
"C+1","C+2","C-1", "C-2",
"C*1", "C*2", "C/1", "C/2"
]
...each of these corresponding to an "odometer" value that
picks an index from each array...
[0,0,0], [0,0,1], [0,1,0], [0,1,1]
[0,2,0], [0,2,1], [0,3,0], [0,3,1]
[1,0,0], [1,0,1], [1,1,0], [1,1,1]
[1,2,0], [1,2,1], [1,3,0], [1,3,1]
[2,0,0], [2,0,1], [2,1,0], [2,1,1]
[2,2,0], [2,2,1], [2,3,0], [2,3,1]
The "odometer" method allows you to easily generate
the type of output you want, not just the concatenated strings
like we have here. Besides that, by avoiding recursion
we avoid the possibility of -- dare I say it? -- a stack overflow...
function combineArrays( array_of_arrays ){
// First, handle some degenerate cases...
if( ! array_of_arrays ){
// Or maybe we should toss an exception...?
return [];
}
if( ! Array.isArray( array_of_arrays ) ){
// Or maybe we should toss an exception...?
return [];
}
if( array_of_arrays.length == 0 ){
return [];
}
for( let i = 0 ; i < array_of_arrays.length; i++ ){
if( ! Array.isArray(array_of_arrays[i]) || array_of_arrays[i].length == 0 ){
// If any of the arrays in array_of_arrays are not arrays or zero-length, return an empty array...
return [];
}
}
// Done with degenerate cases...
// Start "odometer" with a 0 for each array in array_of_arrays.
let odometer = new Array( array_of_arrays.length );
odometer.fill( 0 );
let output = [];
let newCombination = formCombination( odometer, array_of_arrays );
output.push( newCombination );
while ( odometer_increment( odometer, array_of_arrays ) ){
newCombination = formCombination( odometer, array_of_arrays );
output.push( newCombination );
}
return output;
}/* combineArrays() */
// Translate "odometer" to combinations from array_of_arrays
function formCombination( odometer, array_of_arrays ){
// In Imperative Programmingese (i.e., English):
// let s_output = "";
// for( let i=0; i < odometer.length; i++ ){
// s_output += "" + array_of_arrays[i][odometer[i]];
// }
// return s_output;
// In Functional Programmingese (Henny Youngman one-liner):
return odometer.reduce(
function(accumulator, odometer_value, odometer_index){
return "" + accumulator + array_of_arrays[odometer_index][odometer_value];
},
""
);
}/* formCombination() */
function odometer_increment( odometer, array_of_arrays ){
// Basically, work you way from the rightmost digit of the "odometer"...
// if you're able to increment without cycling that digit back to zero,
// you're all done, otherwise, cycle that digit to zero and go one digit to the
// left, and begin again until you're able to increment a digit
// without cycling it...simple, huh...?
for( let i_odometer_digit = odometer.length-1; i_odometer_digit >=0; i_odometer_digit-- ){
let maxee = array_of_arrays[i_odometer_digit].length - 1;
if( odometer[i_odometer_digit] + 1 <= maxee ){
// increment, and you're done...
odometer[i_odometer_digit]++;
return true;
}
else{
if( i_odometer_digit - 1 < 0 ){
// No more digits left to increment, end of the line...
return false;
}
else{
// Can't increment this digit, cycle it to zero and continue
// the loop to go over to the next digit...
odometer[i_odometer_digit]=0;
continue;
}
}
}/* for( let odometer_digit = odometer.length-1; odometer_digit >=0; odometer_digit-- ) */
}/* odometer_increment() */
Just in case anyone is looking for Array.map solution
var array1=["A","B","C"];
var array2=["1","2","3","4"];
console.log(array1.flatMap(d => array2.map(v => d + v)))
Seeing a lot of for loops in all of the answers...
Here's a recursive solution I came up with that will find all combinations of N number of arrays by taking 1 element from each array:
const array1=["A","B","C"]
const array2=["1","2","3"]
const array3=["red","blue","green"]
const combine = ([head, ...[headTail, ...tailTail]]) => {
if (!headTail) return head
const combined = headTail.reduce((acc, x) => {
return acc.concat(head.map(h => `${h}${x}`))
}, [])
return combine([combined, ...tailTail])
}
console.log('With your example arrays:', combine([array1, array2]))
console.log('With N arrays:', combine([array1, array2, array3]))
//-----------UPDATE BELOW FOR COMMENT---------
// With objects
const array4=[{letter: "A"}, {letter: "B"}, {letter: "C"}]
const array5=[{number: 1}, {number: 2}, {number: 3}]
const array6=[{color: "RED"}, {color: "BLUE"}, {color: "GREEN"}]
const combineObjects = ([head, ...[headTail, ...tailTail]]) => {
if (!headTail) return head
const combined = headTail.reduce((acc, x) => {
return acc.concat(head.map(h => ({...h, ...x})))
}, [])
return combineObjects([combined, ...tailTail])
}
console.log('With arrays of objects:', combineObjects([array4, array5, array6]))
A loop of this form
combos = [] //or combos = new Array(2);
for(var i = 0; i < array1.length; i++)
{
for(var j = 0; j < array2.length; j++)
{
//you would access the element of the array as array1[i] and array2[j]
//create and array with as many elements as the number of arrays you are to combine
//add them in
//you could have as many dimensions as you need
combos.push(array1[i] + array2[j])
}
}
Assuming you're using a recent web browser with support for Array.forEach:
var combos = [];
array1.forEach(function(a1){
array2.forEach(function(a2){
combos.push(a1 + a2);
});
});
If you don't have forEach, it is an easy enough exercise to rewrite this without it. As others have proven before, there's also some performance advantages to doing without... (Though I contend that not long from now, the common JavaScript runtimes will optimize away any current advantages to doing this otherwise.)
Solution enhancement for #Nitish Narang's answer.
Use reduce in combo with flatMap to support N arrays combination.
const combo = [
["A", "B", "C"],
["1", "2", "3", "4"]
];
console.log(combo.reduce((a, b) => a.flatMap(x => b.map(y => x + y)), ['']))
Here is functional programming ES6 solution:
var array1=["A","B","C"];
var array2=["1","2","3"];
var result = array1.reduce( (a, v) =>
[...a, ...array2.map(x=>v+x)],
[]);
/*---------OR--------------*/
var result1 = array1.reduce( (a, v, i) =>
a.concat(array2.map( w => v + w )),
[]);
/*-------------OR(without arrow function)---------------*/
var result2 = array1.reduce(function(a, v, i) {
a = a.concat(array2.map(function(w){
return v + w
}));
return a;
},[]
);
console.log(result);
console.log(result1);
console.log(result2)
Part II: After my complicated iterative "odometer" solution of July 2018, here's a simpler recursive version of combineArraysRecursively()...
function combineArraysRecursively( array_of_arrays ){
// First, handle some degenerate cases...
if( ! array_of_arrays ){
// Or maybe we should toss an exception...?
return [];
}
if( ! Array.isArray( array_of_arrays ) ){
// Or maybe we should toss an exception...?
return [];
}
if( array_of_arrays.length == 0 ){
return [];
}
for( let i = 0 ; i < array_of_arrays.length; i++ ){
if( ! Array.isArray(array_of_arrays[i]) || array_of_arrays[i].length == 0 ){
// If any of the arrays in array_of_arrays are not arrays or are zero-length array, return an empty array...
return [];
}
}
// Done with degenerate cases...
let outputs = [];
function permute(arrayOfArrays, whichArray=0, output=""){
arrayOfArrays[whichArray].forEach((array_element)=>{
if( whichArray == array_of_arrays.length - 1 ){
// Base case...
outputs.push( output + array_element );
}
else{
// Recursive case...
permute(arrayOfArrays, whichArray+1, output + array_element );
}
});/* forEach() */
}
permute(array_of_arrays);
return outputs;
}/* function combineArraysRecursively() */
const array1 = ["A","B","C"];
const array2 = ["+", "-", "*", "/"];
const array3 = ["1","2"];
console.log("combineArraysRecursively(array1, array2, array3) = ", combineArraysRecursively([array1, array2, array3]) );
Here is another take. Just one function and no recursion.
function allCombinations(arrays) {
const numberOfCombinations = arrays.reduce(
(res, array) => res * array.length,
1
)
const result = Array(numberOfCombinations)
.fill(0)
.map(() => [])
let repeatEachElement
for (let i = 0; i < arrays.length; i++) {
const array = arrays[i]
repeatEachElement = repeatEachElement ?
repeatEachElement / array.length :
numberOfCombinations / array.length
const everyElementRepeatedLength = repeatEachElement * array.length
for (let j = 0; j < numberOfCombinations; j++) {
const index = Math.floor(
(j % everyElementRepeatedLength) / repeatEachElement
)
result[j][i] = array[index]
}
}
return result
}
const result = allCombinations([
['a', 'b', 'c', 'd'],
[1, 2, 3],
[true, false],
])
console.log(result.join('\n'))
Arbitrary number of arrays, arbitrary number of elements.
Sort of using number base theory I guess - the j-th array changes to the next element every time the number of combinations of the j-1 arrays has been exhausted. Calling these arrays 'vectors' here.
let vectorsInstance = [
[1, 2],
[6, 7, 9],
[10, 11],
[1, 5, 8, 17]]
function getCombos(vectors) {
function countComb(vectors) {
let numComb = 1
for (vector of vectors) {
numComb *= vector.length
}
return numComb
}
let allComb = countComb(vectors)
let combos = []
for (let i = 0; i < allComb; i++) {
let thisCombo = []
for (j = 0; j < vectors.length; j++) {
let vector = vectors[j]
let prevComb = countComb(vectors.slice(0, j))
thisCombo.push(vector[Math.floor(i / prevComb) % vector.length])
}
combos.push(thisCombo)
}
return combos
}
console.log(getCombos(vectorsInstance))
While there's already plenty of good answers to get every combination, which is of course the original question, I'd just like to add a solution for pagination. Whenever there's permutations involved, there's the risk of extremely large numbers. Let's say, for whatever reason, we wanted to build an interface where a user could still browse through pages of practically unlimited permutations, e.g. show permutations 750-760 out of one gazillion.
We could do so using an odometer similar to the one in John's solution. Instead of only incrementing our way through the odometer, we also calculate its initial value, similar to how you'd convert for example seconds into a hh:mm:ss clock.
function getPermutations(arrays, startIndex = 0, endIndex) {
if (
!Array.isArray(arrays) ||
arrays.length === 0 ||
arrays.some(array => !Array.isArray(array))
) {
return { start: 0, end: 0, total: 0, permutations: [] };
}
const permutations = [];
const arrayCount = arrays.length;
const arrayLengths = arrays.map(a => a.length);
const maxIndex = arrayLengths.reduce(
(product, arrayLength) => product * arrayLength,
1,
);
if (typeof endIndex !== 'number' || endIndex > maxIndex) {
endIndex = maxIndex;
}
const odometer = Array.from({ length: arrayCount }).fill(0);
for (let i = startIndex; i < endIndex; i++) {
let _i = i; // _i is modified and assigned to odometer indexes
for (let odometerIndex = arrayCount - 1; odometerIndex >= 0; odometerIndex--) {
odometer[odometerIndex] = _i % arrayLengths[odometerIndex];
if (odometer[odometerIndex] > 0 && i > startIndex) {
// Higher order values in existing odometer are still valid
// if we're not hitting 0, since there's been no overflow.
// However, startIndex always needs to follow through the loop
// to assign initial odometer.
break;
}
// Prepare _i for next odometer index by truncating rightmost digit
_i = Math.floor(_i / arrayLengths[odometerIndex]);
}
permutations.push(
odometer.map(
(odometerValue, odometerIndex) => arrays[odometerIndex][odometerValue],
),
);
}
return {
start: startIndex,
end: endIndex,
total: maxIndex,
permutations,
};
}
So for the original question, we'd do
getPermutations([['A', 'B', 'C'], ['1', '2', '3']]);
-->
{
"start": 0,
"end": 9,
"total": 9,
"permutations": [
["A", "1"],
["A", "2"],
["A", "3"],
["B", "1"],
["B", "2"],
["B", "3"],
["C", "1"],
["C", "2"],
["C", "3"]
]
}
but we could also do
getPermutations([['A', 'B', 'C'], ['1', '2', '3']], 2, 5);
-->
{
"start": 2,
"end": 5,
"total": 9,
"permutations": [
["A", "3"],
["B", "1"],
["B", "2"]
]
}
And more importantly, we could do
getPermutations(
[
new Array(1000).fill(0),
new Array(1000).fill(1),
new Array(1000).fill(2),
new Array(1000).fill(3),
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
['X', 'Y', 'Z'],
['1', '2', '3', '4', '5', '6']
],
750,
760
);
-->
{
"start": 750,
"end": 760,
"total": 1800000000000000,
"permutations": [
[0, 1, 2, 3, "e", "B", "Z", "1"],
[0, 1, 2, 3, "e", "B", "Z", "2"],
[0, 1, 2, 3, "e", "B", "Z", "3"],
[0, 1, 2, 3, "e", "B", "Z", "4"],
[0, 1, 2, 3, "e", "B", "Z", "5"],
[0, 1, 2, 3, "e", "B", "Z", "6"],
[0, 1, 2, 3, "e", "C", "X", "1"],
[0, 1, 2, 3, "e", "C", "X", "2"],
[0, 1, 2, 3, "e", "C", "X", "3"],
[0, 1, 2, 3, "e", "C", "X", "4"]
]
}
without the computer hanging.
Here's a short recursive one that takes N arrays.
function permuteArrays(first, next, ...rest) {
if (rest.length) next = permuteArrays(next, ...rest);
return first.flatMap(a => next.map(b => [a, b].flat()));
}
Or with reduce (slight enhancement of Penny Liu's):
function multiply(a, b) {
return a.flatMap(c => b.map(d => [c, d].flat()));
}
[['a', 'b', 'c'], ['+', '-'], [1, 2, 3]].reduce(multiply);
Runnable example:
function permuteArrays(first, next, ...rest) {
if (rest.length) next = permuteArrays(next, ...rest);
return first.flatMap(a => next.map(b => [a, b].flat()));
}
const squish = arr => arr.join('');
console.log(
permuteArrays(['A', 'B', 'C'], ['+', '-', '×', '÷'], [1, 2]).map(squish),
permuteArrays(['a', 'b', 'c'], [1, 2, 3]).map(squish),
permuteArrays([['a', 'foo'], 'b'], [1, 2]).map(squish),
permuteArrays(['a', 'b', 'c'], [1, 2, 3], ['foo', 'bar', 'baz']).map(squish),
)
I had a similar requirement, but I needed get all combinations of the keys of an object so that I could split it into multiple objects. For example, I needed to convert the following;
{ key1: [value1, value2], key2: [value3, value4] }
into the following 4 objects
{ key1: value1, key2: value3 }
{ key1: value1, key2: value4 }
{ key1: value2, key2: value3 }
{ key1: value2, key2: value4 }
I solved this with an entry function splitToMultipleKeys and a recursive function spreadKeys;
function spreadKeys(master, objects) {
const masterKeys = Object.keys(master);
const nextKey = masterKeys.pop();
const nextValue = master[nextKey];
const newObjects = [];
for (const value of nextValue) {
for (const ob of objects) {
const newObject = Object.assign({ [nextKey]: value }, ob);
newObjects.push(newObject);
}
}
if (masterKeys.length === 0) {
return newObjects;
}
const masterClone = Object.assign({}, master);
delete masterClone[nextKey];
return spreadKeys(masterClone, newObjects);
}
export function splitToMultipleKeys(key) {
const objects = [{}];
return spreadKeys(key, objects);
}
one more:
const buildCombinations = (allGroups: string[][]) => {
const indexInArray = new Array(allGroups.length);
indexInArray.fill(0);
let arrayIndex = 0;
const resultArray: string[] = [];
while (allGroups[arrayIndex]) {
let str = "";
allGroups.forEach((g, index) => {
str += g[indexInArray[index]];
});
resultArray.push(str);
// if not last item in array already, switch index to next item in array
if (indexInArray[arrayIndex] < allGroups[arrayIndex].length - 1) {
indexInArray[arrayIndex] += 1;
} else {
// set item index for the next array
indexInArray[arrayIndex] = 0;
arrayIndex += 1;
// exclude arrays with 1 element
while (allGroups[arrayIndex] && allGroups[arrayIndex].length === 1) {
arrayIndex += 1;
}
indexInArray[arrayIndex] = 1;
}
}
return resultArray;
};
One example:
const testArrays = [["a","b"],["c"],["d","e","f"]]
const result = buildCombinations(testArrays)
// -> ["acd","bcd","ace","acf"]
My version of the solution by John D. Aynedjian, which I rewrote for my own understanding.
console.log(getPermutations([["A","B","C"],["1","2","3"]]));
function getPermutations(arrayOfArrays)
{
let permutations=[];
let remainder,permutation;
let permutationCount=1;
let placeValue=1;
let placeValues=new Array(arrayOfArrays.length);
for(let i=arrayOfArrays.length-1;i>=0;i--)
{
placeValues[i]=placeValue;
placeValue*=arrayOfArrays[i].length;
}
permutationCount=placeValue;
for(let i=0;i<permutationCount;i++)
{
remainder=i;
permutation=[];
for(let j=0;j<arrayOfArrays.length;j++)
{
permutation[j]=arrayOfArrays[j][Math.floor(remainder/placeValues[j])];
remainder=remainder%placeValues[j];
}
permutations.push(permutation.reduce((prev,curr)=>prev+curr,"")); }
return permutations;
}
First express arrays as array of arrays:
arrayOfArrays=[["A","B","C"],["a","b","c","d"],["1","2"]];
Next work out the number of permuations in the solution by multiplying the number of elements in each array by each other:
//["A","B","C"].length*["a","b","c","d"].length*["1","2"].length //24 permuations
Then give each array a place value, starting with the last:
//["1","2"] place value 1
//["a","b","c","d"] place value 2 (each one of these letters has 2 possibilities to the right i.e. 1 and 2)
//["A","B","C"] place value 8 (each one of these letters has 8 possibilities to the right i.e. a1,a2,b1,b2,c1,c2,d1,d2
placeValues=[8,2,1]
This allows each element to be represented by a single digit:
arrayOfArrays[0][2]+arrayOfArrays[1][3]+arrayOfArrays[2][0] //"Cc1"
...would be:
2*placeValues[2]+3*placesValues[1]+0*placeValues[2] //2*8+3*2+0*1=22
We actually need to do the reverse of this so convert numbers 0 to the number of permutations to an index of each array using quotients and remainders of the permutation number.
Like so:
//0 = [0,0,0], 1 = [0,0,1], 2 = [0,1,0], 3 = [0,1,1]
for(let i=0;i<permutationCount;i++)
{
remainder=i;
permutation=[];
for(let j=0;j<arrayOfArrays.length;j++)
{
permutation[j]=arrayOfArrays[j][Math.floor(remainder/placeValues[j])];
remainder=remainder%placeValues[j];
}
permutations.push(permutation.join(""));
}
The last bit turns the permutation into a string, as requested.
Make a loop like this
->
let numbers = [1,2,3,4,5];
let letters = ["A","B","C","D","E"];
let combos = [];
for(let i = 0; i < numbers.length; i++) {
combos.push(letters[i] + numbers[i]);
};
But you should make the array of “numbers” and “letters” at the same length thats it!