Adding elements from each sub array in a 2D array in Javascript - javascript

So I have this 2D permutations array of ints which looks like this:
arr = [
[ 5, 2, 6 ],
[ 2, 5, 6 ],
[ 6, 5, 2 ],
[ 5, 6, 2 ],
[ 2, 6, 5 ],
[ 6, 2, 5 ]
]
and essentially I want to be able to get a string that looks like this '652,625,562,526,256'
This means that the numbers are ordered and are in string format.
What I have done so far is:
arr.map(c => c.join("")).join()
Which combines it to a array, however now my thought process would be to convert this to a array of ints and then order and re-parse as strings, but there must be some kind of easier way to do this?
I'm quite new to JavaScript so any help is appreciated.

Don't do the second join immediately - instead, sort the array of joined strings first, then join:
const arr = [
[ 5, 2, 6 ],
[ 2, 5, 6 ],
[ 6, 5, 2 ],
[ 5, 6, 2 ],
[ 2, 6, 5 ],
[ 6, 2, 5 ]
];
const result = arr
.map(subarr => subarr.join(''))
.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))
.join();
console.log(result);
or map to numbers and subtract in the comparator:
const arr = [
[ 5, 2, 6 ],
[ 2, 5, 6 ],
[ 6, 5, 2 ],
[ 5, 6, 2 ],
[ 2, 6, 5 ],
[ 6, 2, 5 ]
];
const result = arr
.map(subarr => Number(subarr.join('')))
.sort((a, b) => b - a)
.join();
console.log(result);

Related

How to get the same combinations in my array list

I have an array with lists:
[ [ 1, 2 ], [ 3, 5 ], [ 2, 5 ], [ 3, 5 ], [ 1, 2 ] ]
The output im expecting is:
[ [ 1, 2 ], [ 3, 5 ] ]
Im not able to iterate and find duplicates when we have lists in an array.
You can compare two arrays using JSON.stringify. First, call the reduce method on the original array starting with an empty arr as the accumulator, then push each item of the original array inside the acc array only if it hasn’t already been pushed inside acc. In order to check if acc doesn’t already contain that item(array), you can use a method like some and see if any array inside the acc array, is equal to the current array or not.To compare the arrays use JSON.stringify.
const data = [ [ 1, 2 ], [ 3, 5 ], [ 2, 5 ], [ 3, 5 ], [ 1, 2 ] ]
const includesArray = (arr1, arr2) =>
arr1.some(item=>
JSON.stringify(item)==JSON.stringify(arr2));
const result=data.reduce((acc,item)=>
!includesArray(acc,item)?
[...acc,item]:
acc,[]);
console.log(result);
I made the logic, maybe inefficient but it works.
Here's the code:
const sameCombi = (arr) => {
let result = []
arr.forEach((ele) => {
let same = arr.filter((val) => val.join() === ele.join())
if (result.find((valRes) => valRes.join() === ele.join())) return false
if (same.length > 1) result.push(ele)
})
return result
}
console.log(
sameCombi([
[1, 2],
[3, 5],
[2, 5],
[3, 5],
[1, 2]
])
)

How can I make what I want array

I'm a student who has just studied javaScript.
I'm trying to solve an algorithm problem, but I can't solve the problem.
just simple Q ... but I couldn't solve the problem.
[ [ 1, 2 ], [ 1, 3 ], [ 2, 1 ], [ 2, 3 ], [ 3, 1 ], [ 3, 2 ] ]
please advice me How should make it what I want array
I need to turn a 2D array into a 1D array.
result i want [ 1, 2 ], [ 1, 3 ], [ 2, 1 ], [ 2, 3 ], [ 3, 1 ], [ 3, 2 ]
I've tried to do many thing.
At first I thought it would be easy , but I couldn't.
I tried many methods, but I didn't get the result.
let a = [ [ 1, 2 ], [ 1, 3 ], [ 2, 1 ], [ 2, 3 ], [ 3, 1 ], [ 3, 2 ] ]
a.toString().split('').join('')
let result = [];
result.push(a) // [ '1,2', '1,3', '2,1', '2,3' ] // string
How can I get the results [ 1, 2 ], [ 1, 3 ], [ 2, 1 ], [ 2, 3 ], [ 3, 1 ], [ 3, 2 ]?
This is the closest result I get :
let a = [ [ 1, 2 ], [ 1, 3 ], [ 2, 1 ], [ 2, 3 ], [ 3, 1 ], [ 3, 2 ] ]
let res = '';
a.forEach(b => {
res += `[${b}],`
});
console.log(res); // [1,2],[1,3],[2,1],[2,3],[3,1],[3,2],
I hope I helped !
Update
To answer OP from the comments below :
let a = [ [ 1, 2 ], [ 1, 3 ], [ 2, 1 ], [ 2, 3 ], [ 3, 1 ], [ 3,2 ] ]
let res = a.map(cell => cell = +cell.join(''))
console.log(res); // [12, 13, 21, 23, 31, 32]
.map() : see the MDN docs here
On the first call cell will be [ 1, 2 ]. Using .join('') on it will result in "12". Having a + sign before the .join('') call will parse the result in number.
I hope I explained the process well :)
I am trying to understand what you mean here, but i believe what you want is this
let a = [ [ 1, 2 ], [ 1, 3 ], [ 2, 1 ], [ 2, 3 ], [ 3, 1 ], [ 3, 2 ] ];
let arr = [];
for (i=0;i<a.length;++i){
var toTXT = a[i][0]+","+a[i][1];
arr[i] = toTXT;
}
console.log(arr) // (6) ['1,2', '1,3', '2,1', '2,3', '3,1', '3,2']
const arr = [ [ 1, 2 ], [ 1, 3 ], [ 2, 1 ], [ 2, 3 ], [ 3, 1 ], [ 3, 2 ] ];
let newArr = [];
for(let a of arr){
for(let b of a){
newArr.push(b);
}
}
console.log( newArr ); // this is 1 dimensional array.
/*
your request :
[ 1, 2 ], [ 1, 3 ], [ 2, 1 ], [ 2, 3 ], [ 3, 1 ], [ 3, 2 ]
that was an invalid sintax. you cant.
the valid one is :
[ [ 1, 2 ], [ 1, 3 ], [ 2, 1 ], [ 2, 3 ], [ 3, 1 ], [ 3, 2 ] ];
*/

Converting Python enumerate into Javascript

I am trying to convert a function of python code into JavaScript.
The arr variable is an array such as [2, 5, 3, 1]. Basically, I want to create a list of tuple where each tuple contains as first value the position of the element in the arr and as second value the element of the arr. Then, I want to do the same for the reversed of arr
Python code:
def myPositions(arr):
positions = sorted(list(enumerate(arr)), key=lambda e: e[1])
return positions
def final(arr):
print("Reversed", arr[::-1]) # [ 1, 3, 5, 2 ]
print(myPositions(arr)) # [(3, 1), (0, 2), (2, 3), (1, 5)]
print(myPositions(arr[::-1])) # [(0, 1), (3, 2), (1, 3), (2, 5)]
My JavaScript code
Since there is no enumerate in JavaScript (this is what I think), I did the following:
function myPositions(arr) {
let positions = arr.map((e,i) => [i, e]).sort((a, b) => a[1] - b[1] )
return positions
}
function final(arr) {
let reversedArr = arr.reverse()
console.log("Reversed", reversedArr) // [ 1, 3, 5, 2 ]
let x = myPositions(arr)
console.log(x) // [ [ 0, 1 ], [ 3, 2 ], [ 1, 3 ], [ 2, 5 ] ]
let y = myPositions(reversedArr)
console.log(y) // [ [ 0, 1 ], [ 3, 2 ], [ 1, 3 ], [ 2, 5 ] ] This is different than print(myPositions(arr[::-1]))
}
I do not get why it works the same if I do not reverse the array.
But with the reversed array, I get two different results.
In python I get [(0, 1), (3, 2), (1, 3), (2, 5)], in JS I get [ [ 0, 1 ], [ 3, 2 ], [ 1, 3 ], [ 2, 5 ] ]

Why does shifting an array within an array affect copied (not by reference) arrays, but shifting the whole initial array does not? (Javascript)

I am trying to shift an array and use that array, then set it to its original values using a copied array that was copied not by reference. For some reason, shifting arrays from the original array does not affect the copied array, but shifting elements from within arrays in the initial array does affect the copied array. How do I copy an array, modify it, use it, then set it back to its original form?
I originally was having trouble because I was copying by reference, but then I learned that using the rest operator allowed me to copy the array (not by reference). It seems the two datum are still linked.
var m = [[1,2,3],[4,5,6],[7,8,9]]
var matrix = [...m]
m.shift();
console.log(matrix);
m[0].shift();
console.log(m);
console.log(matrix);
Expected:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
[ [ 5, 6 ], [ 7, 8, 9 ] ]
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Actual:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
[ [ 5, 6 ], [ 7, 8, 9 ] ]
[ [ 1, 2, 3 ], [ 5, 6 ], [ 7, 8, 9 ] ]
The problem is that the second degree arrays are still being passed by reference when you do [...m]. I'm not sure how you could still use the rest operator but another thing you could do is:
var matrix = JSON.parse(JSON.stringify(m));
to avoid the problem.
var m = [[1,2,3],[4,5,6],[7,8,9]];
var matrix = JSON.parse(JSON.stringify(m));
m.shift();
console.log(matrix);
m[0].shift();
console.log(m);
console.log(matrix);

JavaScript. Push and read from Multidimensional Array

I am trying to push values into a multidimensional array and read values out of it based on code that i've seen on other posts on this site. This is my array push code.
SelectedWindowGraphs.push([ContainerIDValue,elementID+"chkbox"]);
ContainerIDValue is an integer and elementID+"chkbox" is what i want to store at that position in the array. Here is what i saw when i debugged my code:
This is not what i want. At position 0, i want CUT17chkbox, CUT18chkbox, and CUT19chkbox. How do i fix my array so that i does that?
// initialize an array at that position in case it has not been defined yet
SelectedWindowGraphs[ContainerIDValue] = (SelectedWindowGraphs[ContainerIDValue] ||
[]);
// push the value at the desired position
SelectedWindowGraphs[ContainerIDValue].push(elementID+"chkbox");
You have to push to a subarray:
if(!SelectedWindowGraphs[ContainerIDValue])
SelectedWindowGraphs[ContainerIDValue] = [];
SelectedWindowGraphs[ContainerIDValue]
.push(elementID+"chkbox");
You could add elements at certain position just doing:
var arr = [ 1, 2, 3, 4, 5, 6, 7 ]
arr[2] = "three";
console.log(arr);//[ 1, 2, 'three', 4, 5, 6, 7 ]
In a multidimensional array:
var arr = [ 1, [2, 3, 4, 5, 6], 7 ]
arr[1][2] = "four";
console.log(arr);//[ 1, [ 2, 3, 'four', 5, 6 ], 7 ]
When you perform push you are adding one or more elements at the end.
var arr = [1,2,3]
arr.push(4,5);//you are adding 4 and then 5
console.log(arr);//[ 1, 2, 3, 4, 5 ]
In a multidimensional array:
var arr = [1,2,[3,4]]
arr[2].push(5,6);//position 2
console.log(arr);//[ 1, 2, [ 3, 4, 5, 6 ] ]
To insert an element in a specific position (and move right element n positions) you could use splice(). In the following case, 2th and 3th position
var arr = [ 1, 2, 3, 4, 5 ]
arr.splice(2, 0, 999, 8888);
console.log(arr);//[ 1, 999, 8888, 2, 3, 4, 5 ]
In a multidimensional array:
var arr = [ 1, 2, [3,4,5], 6, 7 ]
arr.splice(2, 0, [8,9,10]);
console.log(arr);//[ 1, 2, [ 8, 9, 10 ], [ 3, 4, 5 ], 6, 7 ]

Categories

Resources