How to get the same combinations in my array list - javascript

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

Related

How to push array inside array of objects?

I have an array. "branches": [1,2,3,4,5,6,7,8,9,10], I need to push this array into an array of objects. Here multipleBranch is the array of objects. How to achieve this in javascript?
multipleBranch: [
{
branches: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
},
]
The simplest solution as per your description
const branches = [1,2,3,4,5,6,7,8,9,10];
const multipleBranch = [{ branches }];
If you want to add multiple branches then check the code below
const multiBranch = [
{
"branches": [1,2,3,4,5,6,7,8,9,10]
}
]
const addBranch = (arr) => {
multiBranch.push({branches:arr});
}
addBranch([1,2,3]);
console.log(multiBranch);

Adding elements from each sub array in a 2D array in 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);

Combine arrays of identical length into array of objects

I have 10 arrays of data that look like this:
var arr = [1,2,3,4,5,6,7,8,9,10]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9']
...8 More Arrays
Each array will have exactly the same number of elements every time. I wanted to know the best way to generate an array of objects that look like this that combines the various arrays:
overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]
I recognize that I can use a large number of for loops but am looking for a more optimized solution that someone might have.
This is where Array.map() will be your friend. You can iterate through any of the arrays (since they have the same number of elements) and then access each element by index to get the corresponding value for each array in your dataset, like so:
var arr = [0,1,2,3,4,5,6,7,8,9]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'];
var arr3=['foo','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9'];
let mapped = arr.map((elem, index) => {
return {
arr1: arr[index],
arr2: arr2[index],
arr3: arr3[index]
}
});
console.log(mapped);
Edit: If you wanted to access them generically, you can add all of your arrays to one dictionary and iterate over the key/value pairs, like so:
var arr = [0,1,2,3,4,5,6,7,8,9]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'];
var arr3=['foo','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9'];
// combine all arrays into single dataset
let data = {arr, arr2, arr3};
let mapped = arr.map((elem, index) => {
// iterate over the key/value pairs of the dataset, use the key to generate the
// result object key, use the value to grab the item at the current index of the
// corresponding array
return Object.entries(data).reduce((res, [key, value]) => {
res[key] = value[index];
return res;
}, {});
});
console.log(mapped);
Assuming arr1,arr2 are not desired names of resulting object properties, if you need something
that scales nicely for arbitrary number of data arrays
assigns arbitrary key names (not necessarily corresponding to array variable names, or, worse, property name(s) that can't be valid variable name are needed)
works muuuch faster than accepted solution ;)
You may do the following:
const arr1 = [1,2,3,4,5,6,7,8,9,10],
arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'],
keyNames = ['id', 'greeting'],
group = (...arrays) => (keys) =>
arrays.reduce((res, arr, idx) =>
(arr.forEach((e,i) => res[i][keys[idx]] = e), res),
Array.from({length:arrays[0].length}, () => ({}))
)
console.log(group(arr1,arr2)(keyNames))
.as-console-wrapper {min-height:100%;}
Just iterate all arrays with 1 loop counter:
var dataArrayOne = [1, 2, 3, 4 ];
var dataArrayTwo = ["hello", "hello1", "hello2", "hello3" ];
...
var resultArray = [];
for (var i = 0; i < 4; i++)
{
var combined = {
arr1: dataArrayOne[I],
arr2: dataArrayTwo[i]
...
};
resultArray.push(combined);
}
You can get from this:
[ [1, 2, 3]
, [4, 5, 6]
, [7, 8, 9]
]
to this:
[ [1, 4, 7]
, [2, 5, 8]
, [3, 6, 9]
]
with this function:
const combine =
(...arrs) =>
[ arrs.map(xs => xs[0])
, ... ( arrs.every(xs => xs.length === 1)
? []
: combine(...arrs.map(xs => xs.slice(1)))
)
];
combine
( [1, 2, 3]
, [4, 5, 6]
, [7, 8, 9]
);
Then from this:
[ [1, 4, 7]
, [2, 5, 8]
, [3, 6, 9]
]
to this:
[ {arr1: 1, arr2: 4, arr3: 7}
, {arr1: 2, arr2: 5, arr3: 8}
, {arr1: 3, arr2: 6, arr3: 9}
]
with this function:
const to_obj =
(...arrs) =>
arrs.map(arr =>
Object.fromEntries(
arr.map((x, i) => [`arr${i+1}`, x])));
to_obj
( [1, 4, 7]
, [2, 5, 8]
, [3, 6, 9]
)
Hopefully connecting the two functions together is straightforward.
A note about performance
With exactly 10 arrays of 10 elements each, it is unlikely that you can tell whether a particular solution performs better than another. You should probably go for the solution that feels right in terms of readability or maintenance.
By these criteria you should probably exclude mine; just wanted to share a different approach.

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

Categories

Resources