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

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

Related

JavaScript Filter And IndexOf Remove Duplicate [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 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)];

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);

Select random values from an array in ascending and descending order [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
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.

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);

I have json file and for each user i am writing into a file using file.write() but it's writing the last user only using javascript [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 3 years ago.
Improve this question
I have json file and for each user i am writing into a file using file.write() but it's writing the last user only using javascript
function getUsers()
{
var allsessions = [1,2,3,4,5]
var allsessiontitle = [a,b,c,d,e]
var usersjson = './users.json';
var usersdata = JSON.parse(fs.readFileSync(usersjson, 'utf8'));
usersdata.forEach // User data
(
(user)=>
{
//console.log(user.FNAME);
var allsessions = [1,2,3,4,5]
user = {...user, MYSESSIONS:allsessions}
//console.log(user)
\
}
)
}
You could take the numerical value of the check.
var array = [1, 2, 3, 4, 1, 2, 1, 3],
result = array.map(v => +(v === 1));
console.log(result);
var array = [1, 2, 3, 4, 1, 2, 1, 3];
console.log(array.map(e => e != 1 ? 0 : e))

Categories