How to push an array into another [closed] - javascript

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

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

JS .includes() with more than one values of array? [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
I have an array of numbers like A = ['1', '34', '23', '55'] and want to use .includes() to find true or false. However, my tested values are in array like B = ['3', '1', '543', '33']
I'd tried to do A.includes(B) but it seems it is not working. A.includes('1', '123') returns true. How can I use my Array B to do the same?
I wanted to Check if the array A has at least one of the array B’s value then return true. Apology for missing this part!
If I understand you correctly, you're looking to do A.includes(B), but your inputs are stored in arrays. In this case, simply loop through the values and call includes() on the elements:
const A = ['1', '34', '23', '55'];
const B = ['3', '1', '543', '33'];
for (var i = 0; i < A.length; ++i)
console.log(A[i].includes(B[i]));
If you need to check if all values in B are in A, you can do it like below:
B.every(item => A.includes(item)) // true or false
includes() does not work this way. Per the Mozilla docs:
arr.includes(valueToFind[, fromIndex])
Where valueToFind is a single value and fromIndex is the index to start looking from. (In your case it looks like it ignored that because it was a string; otherwise it would have returned false.)
If what you want is to find if array A contains every element of array B, there's no standard library function that does exactly that. Here's what you can do:
function containsAll(container, contained) {
return contained.every(item => container.includes(item))
}
containsAll(A, B);
If I understand you correct you want to check if array B all of it's element includes
in array A or not it would be like this using every
B.every((el) => A.includes(el))
let A = [1, 2, 3], B = [2, 3, 4]
let result = B.every((el) => A.includes(el))
console.log(result)
and if you want at least one element from the second array to be in the first one you could do like this using some
B.some((el) => A.includes(el))
let A = [1, 2, 3], B = [2, 3, 4];
let result = B.some((el) => A.includes(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);

Group by operation using one of arrays' values [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 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);

Categories