Turn array element into Object key - JavaScript [duplicate] - javascript

This question already has answers here:
Counting elements in an array and adding them into an object [duplicate]
(2 answers)
Closed 4 years ago.
If I had an array of letters how would I go about turning each letter into an object key with a value of how many there are in that array in JavaScript?
For example:
const array = ['a', 'b', 'c', 'c', 'd', 'a'];
const obj = { a: 2, b: 1, c: 2, d: 1};

Objects can be indexed very similarly to arrays in JavaScript, like so:
const obj = {};
array.forEach((element) => {
//Check if that field exists on the object to avoid null pointer
if (!obj[element]) {
obj[element] = 1;
} else {
obj[element]++;
}
}

you can simply use Array.reduce() to create a frequency map :
const array = ['a', 'b', 'c', 'c', 'd', 'a'];
let result = array.reduce((a, curr) => {
a[curr] = (a[curr] || 0)+1;
return a;
},{});
console.log(result);

Related

Given an array of arrays how do I convert this to an object?

Given an array of arrays, how do I convert this to a JavaScript object with the condition that the first element of each array of the internal arrays will be a key of a new JavaScript object, the subsequent element would be the value?
And if there is more than one occurrence of the element in the first position of the internal arrays only create a single key corresponding to this element.
For example:
var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']]
should return:
var obj = {a: ["b", "e"], c: ["d"]}
Here there are 2 occurrences of a within arr therefore only a single key a was created in obj along with c
Using Array.prototype.reduce function, you can accomplish this as follows.
var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']];
const output = arr.reduce((acc, cur) => {
acc[cur[0]] ? acc[cur[0]].push(cur[1]) : acc[cur[0]] = [ cur[1] ];
return acc;
}, {});
console.log(output);
This is an alternative:
var arr = [['a', 'b'], ['c', 'd'], ['a', 'e']]
const obj = {}
arr.forEach(([k, v]) => obj[k] = [...obj[k] ?? [], v])

How to combine arrays into array of arrays? [duplicate]

This question already has answers here:
Append Multi-Dimension Arrays Horizontally in Blocks
(2 answers)
Closed 4 years ago.
So, I have this 2 arrays:
var num = [1, 2, 3];
var letters = ['a', 'b', 'c'];
I need to combine it to something like this:
var result = [[1, 'a', 'numberandletters'],[2, 'b', 'numberandletters'],[3, 'c', 'numberandletters']]
The third element inside the array is constant when it is being filled. My code so far is this:
for (var x=0; x=3; x++)
result[x] = [num[x], letters[x], 'numberandletters']
But I need to execute it without looping statement.
Is there any function or something I can use to combine these arrays?
var num = [1, 2, 3];
var letters = ['a', 'b', 'c'];
num.map((n,i) => Array(n, letters[i], 'nummberAndLetters'))
Output: As you expected.
If you want it as a function then,
function getCombinedArray(num, letter) {
return num.map((n,i) => Array(n, letters[i], 'nummberAndLetters'));
}
getCombinedArray(num, letters);
Okay. This is what it will be when you don't want to use loop.
const num = [1, 2, 3]
const letters = ['a', 'b', 'c']
let result = [
[
num[0],
letters[0],
'numberandletters'
],
[
num[1],
letters[1],
'numberAndLetter'
],
[
num[2],
letters[2],
'numberAndLetter'
]
]
console.log(result)

Find number of non duplicate items in 2 different arrays with JavaScript? [duplicate]

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Compare 2 arrays which returns difference
(10 answers)
Closed 4 years ago.
I need to find the number of items in two arrays which are not duplicate.
Eg here the answer is 1:
const array1 = ['a', 'b', 'c', 'c']
const array2 = ['a', 'b', 'c']
Eg here the answer is 2:
const array1 = ['a', 'b']
const array2 = ['a', 'x', 'y']
My solution works for some inputs but not all:
function something(a, b) {
let aArray = a.split("");
console.log(aArray);
let bArray = b.split("");
console.log(bArray);
aArray.forEach((aItem, aIndex)=> {
console.log(aItem)
bArray.forEach((bItem, bIndex)=> {
console.log(bItem);
if(aItem === bItem) {
console.log(aIndex, bIndex);
aArray[aIndex] = "-";
bArray[bIndex] = "-";
}
});
});
console.log(aArray);
console.log(bArray);
const aRes = aArray.filter(item=> item !== "-").length;
console.log(aRes)
const bRes = bArray.filter(item=> item !== "-").length;
console.log(bRes)
const res = aRes + bRes;
console.log(res)
return res;
}
Stealing from this: https://stackoverflow.com/a/33034768/4903754
let difference = arr1
.filter(x => !arr2.includes(x))
.concat(arr2.filter(x => !arr1.includes(x)));

referencing an array javascript [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 8 years ago.
Working with the following code:
Array0 = ['a', 'b', 'c'];
Array1 = ['c', 'd', 'e'];
Array2 = ['x', 'a', 'd'];
...
/*
doStuff() is a recursive function whose argument is an abitrary length array
containing an arbitrary list of array names
e.g., anArr = ['Array1', 'Array0', 'Array1', 'Array2', ...]
*/
function doStuff(anArr) {
for(i=0; i<anArr.length; i++) {
switch(anArr[i]) {
case('Array0') : Array0.myMethod(); break;
case('Array1') : Array1.myMethod(); break;
case('Array2') : Array2.myMethod(); break;
}
}
}
Is there a way to replace the switch() block with a single statement:
<<array referenced by 'someArray'>>.aMethod() //or
function aFunction (<<array referenced by 'someArray'>>){}
Plain Javascript, please - no jquery or other library.
Thanks
Use an object in the first place.
var foo = {
Array0 : ['a', 'b', 'c'];
Array1 : ['c', 'd', 'e'];
Array2 : ['x', 'a', 'd'];
}
Then you can:
foo[anArr[i]].myMethod();
You can store the actual arrays in the array...
Array0 = ['a', 'b', 'c'];
Array1 = ['c', 'd', 'e'];
Array2 = ['x', 'a', 'd'];
var anArr = [Array0, Array1, Array2];
for(i=0; i<anArr.length; i++) {
anArr[i].myMethod();
}

Most effective and elegant way to find matching Strings in two arrays in Node.js [duplicate]

This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 8 years ago.
I have 2 string arrays:
var X = ['A', 'B', 'C'],
Y = ['B', 'C', 'D'];
I need to create an array Z, such that Z = A ∩ B
Z = ['B', 'C'];
Z contains the strings that are both in X and Y.
I've done it this way:
A.forEach(function(i) {
B.forEach(function(j) {
if (i === j) Z.push(i);
});
});
Any suggestions / comments?
I'd better use filter method:
['A', 'B', 'C'].filter(function(c) {
return ['B', 'C', 'D'].indexOf(c) > -1;
});

Categories