Group by operation using one of arrays' values [closed] - javascript

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 5 years ago.
Improve this question
I have array of arrays in javascript that looks like: [[1, 23.34, -5.22], [1, 2.34, -52.22], [2, 0.34, -5.02], ...]. I need to group by by the first number in the arrays and produce 2 different ouputs:
Object (key: 2D array) that looks like this:
{1: [[23.34, -5.22], [2.34, -52.22]],
2: [[0.34, -5.02], ...],
...}
3D array that would just signify the grouping:
[[[23.34, -5.22], [2.34, -52.22]], [[0.34, -5.02], ...], ...]
I want to use ES6. Any suggestions would be greatly appreciated.

checkout this code
let array = [[1, 23.34, -5.22], [1, 2.34, -52.22], [2, 0.34, -5.02]];
let obj = {};
array.forEach(subArray =>
{
let key = subArray[0];
if(!obj[key])
obj[key] = [];
subArray.splice(0,1);
obj[key].push(subArray);
});
console.log(obj);
let keys = Object.keys(obj);
let array3D = [];
keys.forEach(key => {
array3D.push(obj[key])
});
console.log(array3D);

There's already a answer which uses map method but I find using forEach in this case more appropriate.
const a = [
[1, 23.34, -5.22], [1, 2.34, -52.22], [2, 0.34, -5.02]
];
let b = {};
let c = [];
a.forEach(x=>{
if(!b[x[0]]){
b[x[0]] = [];
}
b[x[0]].push(x.slice(1));
});
console.log(b);
Object.values(b).forEach(x => c.push(x));
console.log(c);

Related

Compare 2 variables with comma separated values 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 1 year ago.
Improve this question
I have 2 variables say a=1,2,3,4 and b=1,2 , I want to compare these 2 variables and form a new variable with common values, please help me
Assuming you meant:
a="1,2,3,4"
b="1,2"
You could break those comma delimited values into arrays and then get the intersections of the arrays. Here's an example:
const ArrayA = a.split(",");
const ArrayB = b.split(",");
const intersection = ArrayA.filter(value => ArrayB.includes(value));
const commonCSV = intersection.join(",");
var a = [1, 2, 3, 4];
var b = [1, 2];
// Take unqiue values from a and concat with unique values from b
const occurrenceMap = [...new Set(a)].concat([...new Set(b)]).reduce((map, el) => {
map.set(el, map.get(el) ? map.get(el) + 1 : 1);
return map;
}, new Map());
const common = [];
// Iterate over the map entries and keep only the ones that occur more than once - these would be the intersection of the 2 arrays.
for (entry of occurrenceMap) {
const [key, val] = entry;
if (val > 1) {
common.push(key);
}
}
console.log(common);

How to push an array into another [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 2 years ago.
Improve this question
A very basic question but still learning.
I have a 1D array say = [a,b,c].
and another 2D array = [[1,2,3],[4,5,6],[7,8,9]].
How do I push the array into beginning of each row of 2D array so that my array result looks like this.
[[a,1,2,3],[b,4,5,6],[c,7,8,9]].
You can iterate each item from 2D array and add 1D array value into it.
For more help please check Unshift
var test = ['a', 'b', 'c'];
var tests = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
var index = 0;
tests.map(item => { //Iterate each item from 2D araay
if (index < test.length) { // Check if we have any item in 1D array to avoid crash
item.unshift(test[index++]); // Unshift each item so you can add value at 0 index.
}
});
console.log(tests);
array1 = ["a","b","c"];
array2 = [[1,2,3],[4,5,6],[7,8,9]];
for(var i = 0; i< array2.length;i++){
array2[i].unshift(array1[i]);
}
console.log(array2);
You can loop over one of the array and use unshift to push value at 0 index.
var x = ['a','b','c'];
var y = [[1,2,3],[4,5,6],[7,8,9]];
y.forEach((item, index) => item.unshift(x[index]));
console.log(y);
Here a solution with .map() and the rest operator
let singleArr = ["a","b","c"];
let multiArr = [[1,2,3],[4,5,6],[7,8,9]];
let result = multiArr.map((el, i) => [singleArr[i],...el])
console.log(result);

Best way to compare elements in an array using javascript? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
How do I compare elements in an array using Javascript?
I want to know if cas[1], cas[2] and cas[3] have the same value.
cas = ["0","1", "2","3","4","5","6","7","8","9"];
if(cas[1]== cas[2] && cas[2]==cas[3]){
console.log("yea");
}
The first of all it's better to use ===, because 0 == false is true, but 0 === false is false.
=== works without type casting.
You don't need full cycle loop here, you have to compare only the first 3 elements so if statement is ok here.
If you want to do that with every 3 elements, you can do something like this.
const getThreeArrayElements = (array, startIndex) => array.slice(startIndex, startIndex + 3);
getThreeArrayElements([1, 2, 3, 3, 3, 3], 0); // [1, 2, 3]
getThreeArrayElements([1, 2, 3, 3, 3, 3], 3); // [3, 3, 3]
So you can easily get an array with 3 required elements.
The another task is how to compare them.
const areArrayElementsEqual = array => array.every(item => item === array[0]);
areArrayElementsEqual([1, 2, 3]); // false
areArrayElementsEqual([3, 3, 3]); // true
if you're looking for an algorithm to check the entire array :
let cas = ["0","1", "2","3","4","5","6","7","8","9"];
let checkCas = (cur = 1)=>{return cas[cur-1]===cas[cur]?true:cur<cas.length?checkCas(++cur):false;};
console.log(checkCas());
cas = ["0","1", "2","3","4","5","5","7","8","9"];
console.log(checkCas());
as for ticktacktoe :
let casa = ["0","1", "2","3","4","5","6","7","8","9"];
let allEqual = (cas,cur = 1)=>{return cas[cur-1]===cas[cur]?true:cur<cas.length?allEqual(cas,++cur):false;};
for(let i = 0;i<Math.floor(casa.length/3);i++)
{
let tempLengArr = [casa[i],casa[i+3],casa[i+6]];
if(allEqual(casa.slice(i*3,(i*3)+3))||allEqual(tempLengArr))
console.log("won");
}
if(allEqual([casa[0],casa[4],casa[9]])||
allEqual([casa[3],casa[4],casa[2]])) console.log("won");
might have messed up a bit on my allEqual call but it's an idea

Merge 2 arrays in change [duplicate]

This question already has answers here:
Zip arrays in JavaScript?
(5 answers)
Closed 3 years ago.
I wanted to merge two arrays like you can fold 2 packs of cards - in ugly code with for loop and assuming same length so no if's for safety it would look like this:
const arr = [1,2,3];
const rra = [4,5,6];
const result = [];
for(let i=0; i<arr.length; i++){
result.push(arr[i],rra[i]);
}
console.log(result); // Array(6) [ 1, 4, 2, 5, 3, 6 ]
I know there is something similar in String.raw() but it cuts off last element and returns a string, is there equivalent in array ?
String.raw({raw: [1,2,3]}, ...[4,5,6]); //"14253"
You can use .flatMap() for this - This is the same as .map(), followed by .flat()
const arr = [1,2,3];
const rra = [4,5,6];
let newArray = arr.flatMap((ele, i) => [ele, rra[i]]);
console.log(newArray);

Find if object key is in array 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 3 years ago.
Improve this question
So I have an array of ids, consider the following
let ids = [1,2,3]
then an object, consider the following
let obj = {1:true, 2:true, 100:true}
how can i find if the object key is in the array, because the structure is weird it doesn't come with something you usually see like
let obj = { id: 1, value:true}
it just has the key as the id and the value as the right side of the key value
All found id and mapping with an object.
let ids = [1, 2, 3],
obj = { 1: true, 2: true, 100: true },
result = ids
.filter(k => k in obj)
.map(id => ({ id, value: obj[id] }));
console.log(result);
A first found result
let ids = [1, 2, 3],
obj = { 1: true, 2: true, 100: true },
result = (id => ({ id, value: obj[id] }))(ids.find(k => k in obj));
console.log(result);
let ids = [1,2,3]
let obj = {1:true, 2:true, 100:true}
// test if the object has at least one key that is listed in [ids]
console.log(Object.keys(obj).some(x => ids.includes(Number(x)))); // true
// get the object keys that exist in [ids] and convert them to numbers
console.log(Object.keys(obj).filter(x => ids.includes(Number(x))).map(x=>Number(x))); // [1,2]
let ids = [1,2,3];
let obj = {1:true, 2:true, 100:true};
let result = Object.keys(obj).filter(id => {
if(ids.indexOf(Number(id))>-1){return true}
})
result is an array with matched ids.

Categories