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);
Related
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 4 days ago.
Improve this question
I am looking for question "Remove a duplicate element from given array and return unique element".
I've tried this code:
var arr = [4, 3, 6, 7, 10, 4, 5, 2];
function removeDuplicates(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index);
}
console.log(removeDuplicates(arr));
There is a way with Set
const removeDuplicates = (arr) => [...new Set(arr)]
console.log(removeDuplicates([1,1,1,2,2,3,4,5,5, 4, 2 , 3,6]))
Your code is OK, but you can simply use Set, a data structure that allows you to create a collection of unique values.
const uniqueArr = [...new Set(arr)];
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
In JavaScript, I'm trying to select random elements from an array, either in ascending and descending order. I would like to create a function that takes an array to select from, the number of elements to select and the random order (either ascending or descending). How can I go about doing this?
e.g
let ar = [a,b,c,d,e,f,g,h,i,j,k,l]
selectRandom(ar, 4, 'ascending')
// returns [b,e,f,j]
selectRandom(ar, 6, 'descending')
// returns [l,j,f,e,b,a]
You could build random arrays and sort them as result.
const
getValues = (array, size) => {
const values = new Set;
while (values.size < size) values.add(array[Math.floor(Math.random() * array.length)]);
return [...values];
},
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
up = 4,
down = 7,
result = [
...getValues(array, up).sort((a, b) => a - b),
...getValues(array, down).sort((a, b) => b - a)
];
console.log(...result);
Maybe something like this:
let array = [1,2,3,4,5,6,7,8,9,10,11,12]
const up = 4
const down = 7
let outputRadnomUpDown = new Array(up).fill(null).map(() => array[~~(Math.random() * array.length)]).sort(function(a, b){return a-b}).concat(new Array(down).fill(null).map(() => array[~~(Math.random() * array.length)]).sort(function(a, b){return b-a}));
console.log(outputRadnomUpDown);
PS: I've edited the answer because by mistake I've switch the number of up/down elements in my previous proposition.
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);
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
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);