How to arrange items in an array in all possible ways? - javascript

Items in an array can be arranged in ascending order using sort() method in JavaScript but how to arrange them in all possible ways and show them in our web page.

You describe permutations, one way to implement it:
function permutations(arr, r=[]) {
if (arr.length === 0) {
console.log(r)
} else {
const first = arr[0]
for (let i = 0; i <= r.length; i++) {
permutations(arr.slice(1), r.slice(0, i).concat([first]).concat(r.slice(i)))
}
}
}
permutations([1, 2, 3])
OUTPUT
[ 3, 2, 1 ]
[ 2, 3, 1 ]
[ 2, 1, 3 ]
[ 3, 1, 2 ]
[ 1, 3, 2 ]
[ 1, 2, 3 ]

Related

Confused about pushing array into array, JavaScript

My code looks like this
var res = [];
var temp = [];
function Permutations(target, size) {
if (size === 0) {
res.push(temp);
console.log(res);
return;
}
for (let i = 0; i < target.length; i++) {
if (target[i] !== null) {
temp.push(target[i]);
target[i] = null;
Permutations(target, size - 1);
target[i] = temp.pop();
}
}
}
Permutations([1, 2, 3], 2);
console.log(res);
When I run my code, I can see my res stores each permutation as it is is being executed. However, when I log it outside the function, all the stored value disappeared.
[ [ 1, 2 ] ]
[ [ 1, 3 ], [ 1, 3 ] ]
[ [ 2, 1 ], [ 2, 1 ], [ 2, 1 ] ]
[ [ 2, 3 ], [ 2, 3 ], [ 2, 3 ], [ 2, 3 ] ]
[ [ 3, 1 ], [ 3, 1 ], [ 3, 1 ], [ 3, 1 ], [ 3, 1 ] ]
[ [ 3, 2 ], [ 3, 2 ], [ 3, 2 ], [ 3, 2 ], [ 3, 2 ], [ 3, 2 ] ]
[ [], [], [], [], [], [] ] // This is my console.log outside the function
The array temp holds is the same array throughout the complete execution of your code. And res.push(temp); adds this same array (not a copy of it) to your res array.
Here a related question about how Objects are handled in JavaScript: Is JavaScript a pass-by-reference or pass-by-value language?
So your code results in res having N times the same array.
You could copy the element stored in temp to a new array using [...temp], and push that to your res array.
var res = [];
var temp = [];
function Permutations(target, size) {
if (size === 0) {
res.push([...temp]);
return;
}
for (let i = 0; i < target.length; i++) {
if (target[i] !== null) {
temp.push(target[i]);
target[i] = null;
Permutations(target, size - 1);
target[i] = temp.pop();
}
}
}
Permutations([1, 2, 3], 2);
console.log(res);

How to dynamically build a javascript Object and push into Array within nested loop?

I'm trying to dynamically build Objects and push them one by one into an Array.
My code so far is this:
matrix([[0,1,1], [1,00], [1,1,1])
const matrix = (sequence) => {
const rows = {}
const rowsAry = []
let row
let idx
for (let i=0; i < samples.length; i++) {
row = `row${i}`
for (let j=0; j < samples[i].length; j++) {
if (samples[i][j] === 1) {
idx = []
rows[row] = rows[row] + 1 || 1
rows['indeces'] = idx.push(j)
rowsAry.push(rows)
}
}
}
console.log(rowsAry)
}
This obviously isn't working. I'm trying to map out all the '1's' in the sequence and know how many are in a row and what there indices are.
The wrong out put is:
[ { row0: 3, indeces: 1, row1: 2, row2: 2 },
{ row0: 3, indeces: 1, row1: 2, row2: 2 },
{ row0: 3, indeces: 1, row1: 2, row2: 2 },
{ row0: 3, indeces: 1, row1: 2, row2: 2 },
{ row0: 3, indeces: 1, row1: 2, row2: 2 },
{ row0: 3, indeces: 1, row1: 2, row2: 2 },
{ row0: 3, indeces: 1, row1: 2, row2: 2 },
{ row0: 3, indeces: 1, row1: 2, row2: 2 },
{ row0: 3, indeces: 1, row1: 2, row2: 2 } ]
Hoped for output would be:
[{row1: 2, indices: [1,2]},
{row2: 1, indices: [0]},
{row3: 3, indices: [0,1,2]}
]
You need to create a new object each time through the outer loop. And only push it onto rowsAry once, not each time through the inner loop.
const matrix = (samples) => {
const rowsAry = []
for (let i = 0; i < samples.length; i++) {
let row = `row${i}`
let indices = [];
for (let j = 0; j < samples[i].length; j++) {
if (samples[i][j] === 1) {
indices.push(j);
}
}
rowsAry.push({[row]: indices.length, indices: indices});
}
console.log(rowsAry)
}
matrix([
[0, 1, 1],
[1, 00],
[1, 1, 1]
])
You can solve it by simply using array map and forEach method. Traverse the array of arrays and check for ones to the inside array by using array forEach method and if found put it to the resultant array. At last, using the resultant array make your required object.
const matrix = (sequence) => {
return sequence.map((x, i) => {
const ret = [];
x.forEach((y, j) => {
if (y === 1) ret.push(j);
});
const key = `row${i + 1}`;
const obj = { [key]: ret.length, indices: ret };
return obj;
});
};
const ret = matrix([
[0, 1, 1],
[1, 0, 0],
[1, 1, 1],
]);
console.log(ret);
Or nested reduce() calls...
const matrix = (sequence) => {
return sequence.reduce((a, r, i) => {
indices = r.reduce((ra, rn, ri) => {
if (rn === 1) ra.push(ri);
return ra;
}, []);
a.push({[`row${i}`]: indices.length, indices: indices});
return a;
}, []);
}
console.log(matrix([[0,1,1], [1,0,0], [1,1,1]]))
But in reference to Barmar's comment about using different rowX keys a more accessible shape for your objects might look something along the lines of
{row: 1, count: 2, indices: [1, 2]}

How to map array into another array of object

Json 1
{
"ordering_data": [
{
"order": 0,
"section_menu_id": 3
},
{
"order": 1,
"section_menu_id": 1
},
{
"order": 2,
"section_menu_id": 6
},
]
}
Json 2
[
3,
7,
4,
]
Expected result
{
"ordering_data": [
{
"order": 3,
"section_menu_id": 3
},
{
"order": 7,
"section_menu_id": 1
},
{
"order": 4,
"section_menu_id": 6
},
]
}
I got 2 json files. can someone tell me how to change the data structure to expected result .I have tried map but it kinda confused for me. Need some help .Thanks in advance.
You can use Array.prototype.map to accomplish this.
On Array.map, through the reference, the second param represents the current index of the array so based on that value, you can assign second array value to order key by index.
const input1 = {
"ordering_data": [
{
"order": 0,
"section_menu_id": 3
},
{
"order": 1,
"section_menu_id": 1
},
{
"order": 2,
"section_menu_id": 6
},
]
};
const input2 = [
3,
7,
4,
];
const updatedOrderingData = input1.ordering_data.map((item, index) => ({
...item,
order: input2[index]
}));
const result = {
ordering_data: updatedOrderingData
};
console.log(result);
I think you are looking for something like the below code snippet.
This assumes that both objects are of equal length, and we are modifying the original object.
First, loop the array, and replace the order in the original object with the numbers in the array.
Make it an exercise to create a new object instead of modifying the original obj1
var obj1 = {
"ordering_data": [
{
"order": 0,
"section_menu_id": 3
},
{
"order": 1,
"section_menu_id": 1
},
{
"order": 2,
"section_menu_id": 6
},
]
};
var myArray = [
3,
7,
4,
];
for(var i = 0; i<myArray.length; i++){
obj1.ordering_data[i].order = myArray[i];
}
console.log(obj1);
This might help.
j1 = {
"ordering_data": [
{
"order": 0,
"section_menu_id": 3
},
{
"order": 1,
"section_menu_id": 1
},
{
"order": 2,
"section_menu_id": 6
},
]
};
j2 = [
3,
7,
4,
]
for(i=0; i<j1.ordering_data.length; i++ ){
j1.ordering_data[i].order = j2[i]
}

matrix to array with every other row reversed

I have to convert matrix to array. For example
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ],
]
should convert to [1, 2, 3, 6, 5, 4, 7, 8, 9 ].
I write a code
function sortMatrix (matrix) {
let newArr = [];
for(let i = 0; i < matrix.length; i++)
{
newArr = newArr.concat(matrix[i]);
}
return newArr
}
but output is [1, 2, 3, 4, 5, 6, 7, 8, 9 ]. How can I do so that on the second line, it counts from the end
To fix your code - reverse sub-arrays at odd indexes.
Note: since Array.reverse() mutates the original array, we need to shallow clone it using array spread.
function sortMatrix(matrix) {
let newArr = [];
for (let i = 0; i < matrix.length; i++) {
const arr = matrix[i];
newArr = newArr.concat(i % 2 ? [...arr].reverse() : arr);
}
return newArr;
}
const matrix = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ],
];
const result = sortMatrix(matrix);
console.log(result);
Another option is to use Array.flatMap(), and reverse sub-arrays at odd indexes.
function sortMatrix(matrix) {
return matrix.flatMap((arr, i) => i % 2 ? [...arr].reverse() : arr);
}
const matrix = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ],
];
const result = sortMatrix(matrix);
console.log(result);
You can use reduce to create it.
const arr = [
[1,2,3],
[4,5,6],
[7,8,9]
]
const flatArray = (arr) => arr.reverse().reduce((acc, curr)=> {
acc.push(...curr.reverse());
return acc;
},[])
console.log(flatArray(arr))
You can directly use the flat function
array = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ],
]
console.log(array.flat());

I think I am using the splice method incorrectly

I am trying to solve a problem and I have having a hard time getting the answer from my splice method. I am trying to pull out all the odd numbers from an array, put them in order, and place them back in the array while leaving the even numbers in place. In my last for loop I am attempting to use splice to get the index of the current odd number, remove it, and put the sorted odd number back in with via a variable. It's not going the way I intended. Thanks for any help I can get.
function sortArray(array) {
var odds = [];
for (var i = 0; i < array.length; i++) {
if (array[i] % 2 !== 0) {
odds.push(array[i]);
}
}
odds.sort();
console.log('array', array)
for (var j = 0; j < array.length; j++) {
var x = 0;
if (array[i] % 2 !== 0) {
x = odds.shift();
console.log('x', x)
array.splice(i, 1, x); <-- I think this is my problem...maybe...
console.log('array 2', array)
}
}
console.log(array)
return array;
}
sortArray([5, 3, 2, 8, 1, 4])
These are the console logs I am getting from it:
array [ 5, 3, 2, 8, 1, 4 ]
x 1
array 2 [ 5, 3, 2, 8, 1, 4, 1 ]
x 3
array 2 [ 5, 3, 2, 8, 1, 4, 3 ]
x 5
array 2 [ 5, 3, 2, 8, 1, 4, 5 ]
x undefined
array 2 [ 5, 3, 2, 8, 1, 4, undefined ]
x undefined
array 2 [ 5, 3, 2, 8, 1, 4, undefined ]
x undefined
array 2 [ 5, 3, 2, 8, 1, 4, undefined ]
x undefined
array 2 [ 5, 3, 2, 8, 1, 4, undefined ]
[ 5, 3, 2, 8, 1, 4, undefined ]
=> [ 5, 3, 2, 8, 1, 4, undefined ]
splice expect two arguments
Index of element from where you want to start deletion.
Number of items to be deleted.
so in your code.
Step-1 : create Odd number array
Step-2 : sort it
Step-3 : remove odd number from existing array
step-4 : concat odd number array to the end of existing array.
Step-1 & 2 are fine
for step -3 & 4
for (var j = 0; j < array.length; j++) {
var x = 0;
if (array[j] % 2 !== 0) {
array.splice(j, 1);
}
}
array = array.concat(odds);

Categories