Deleting arrays of same elements in 2 dimensional array in Javascript - javascript

I am wondering how you would go about deleting arrays that contain the same elements in a 2 dimensional array.
For example:
let 2dArr = [ [1, 2, 3],
[3, 2, 1],
[2, 4, 5],
[4, 5, 2],
[4, 3, 1] ];
This array would delete the second and fourth elements, returning the 2d array:
returnedArr = [ [1, 2, 3],
[2, 4, 5],
[4, 3, 1] ];
How exactly could this be done, preserving the 2d array? I could only think to loop through elements, comparing elements via a sort, and deleting them as you go along, but this would result in an indexing error if an element is deleted.

1) You can easily achieve the result using reduce and Set as:
let twodArr = [
[1, 2, 3],
[3, 2, 1],
[2, 4, 5],
[4, 5, 2],
[4, 3, 1],
];
const set = new Set();
const result = twodArr.reduce((acc, curr) => {
const key = [...curr].sort((a, b) => a - b).join();
if (!set.has(key)) {
set.add(key);
acc.push(curr);
}
return acc;
}, []);
console.log(result);
2) You can also use filter as:
let twodArr = [
[1, 2, 3],
[3, 2, 1],
[2, 4, 5],
[4, 5, 2],
[4, 3, 1],
];
const set = new Set();
const result = twodArr.filter((curr) => {
const key = [...curr].sort((a, b) => a - b).join();
return !set.has(key) ? (set.add(key), true) : false;
});
console.log(result);

const seen = []
const res = array.filter((item) => {
let key = item.sort().join()
if(!seen.includes(key)){
seen.push(key)
return item
}
})
console.log(res)

You can use hash map
let arr = [ [1, 2, 3], [3, 2, 1],[2, 4, 5],[4, 5, 2],[4, 3, 1] ];
let obj = {}
let final = []
for(let i=0; i<arr.length; i++){
// create a key
let sorted = [...arr[i]].sort((a,b)=> a- b).join`,`
// check if this is not present in our hash map
// add value to final out and update hash map accordingly
if(!obj[sorted]){
obj[sorted] = true
final.push(arr[i])
}
}
console.log(final)

Using Array.prototype.filter() and a Set as thisArg
let arr = [ [1, 2, 3],
[3, 2, 1],
[2, 4, 5],
[4, 5, 2],
[4, 3, 1] ];
let res = arr.filter(function(e){
const sorted = [...e].sort((a,b) => a-b).join('|');
return this.has(sorted) ? false : this.add(sorted)
},new Set)
console.log(res)

Related

How to group two-dimensional array by value at zero index

Let's say I have the following two-dimensional array:
const array = [[1, 1], [1, 2], [2, 1], [2, 2]];
What I want to do is to find all the values under first index which have common zero index value. So the result should be the following:
[[1, [1, 2]], [2, [1, 2]]]
Or maybe Map would look better:
[Map(1 => [1, 2]), Map(2 => [1, 2])]
How can I do that? With or without lodash. My solution looks a bit bloated and messy:
const array = [[1, 1], [1, 2], [2, 1], [2, 2]];
const grouppedCartItemsMap = new Map();
array.forEach((item) => {
const [locationId, contractId] = item;
if (!grouppedCartItemsMap.has(locationId)) {
grouppedCartItemsMap.set(locationId, [contractId]);
} else {
const existingItem = grouppedCartItemsMap.get(locationId);
if (!existingItem.includes(contractId)) {
grouppedCartItemsMap.set(locationId, [...existingItem, contractId]);
}
}
});
console.log(grouppedCartItemsMap);
If an object would work:
const array = [[1, 1], [1, 2], [2, 1], [2, 2]];
const grouped = {};
for (const [first, last] of array) {
grouped[first] ??= [];
grouped[first].push(last);
}
console.log(grouped);
This looks like a use case for reduce:
const array = [[1, 1], [1, 2], [2, 1], [2, 2]];
const grouppedCartItemsMap = array.reduce((acc, [locationId, contractId]) => {
if (!acc.has(locationId)) acc.set(locationId, [contractId]);
else acc.get(locationId).push(contractId);
return acc;
}, new Map());
console.log([...grouppedCartItemsMap.entries()]);

How to map an array of arrays and just return it

I have an array of arrays, and I want to map over it and just return the values of arrays, but when I map over it and log the result, it's just an array and I don't know how to map over my array and use it in other places.
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const arrMap = arr.map((it) => it.map((itm) => itm));
console.log(arrMap);
//what I expected 1,2,3,4,5,6 , ...
//what I got [Array(3), Array(3), Array(3)]
Actually, I need the values for using them in somewhere else, but I don't know what to do.
I also used function for this but when I return the values and log them It's undefined:
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const arrMap = (arr) => {
arr.forEach((element) => {
console.log(element);
//In here, everything works fine
return element;
});
};
console.log(arrMap);
//what I got undefined
Use flatMap -
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const arrMap = arr.flatMap(m => m);
console.log(arrMap);
Why it won't work : map() is supposed to run on each element of an array and return a transformed array of the same length. You have three elements in your input array and will always get three elements in your mapped array.
Your expectations can be met by tweaking your code with forEach() if you want. With forEach() there is nothing returned and you will have to start with a separate array variable. Below code uses ...
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
let arrMap = [];
arr.forEach((it) => arrMap.push(...it));
console.log(arrMap);
But flatMap() is already there:
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
let ans = arr.flatMap(x => x);
console.log(ans);
Use flat if you just want to flatten the array:
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
console.log(arr.flat());
Use flatMap if you want to do something with each element before the array gets flattened.
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const arrMap = arr.flatMap((el) => {
el.forEach((n) => console.log(n));
return el;
});
console.log(arrMap);
forEach doesn't return anything it's like a for loop but for array only.
Since you have double array you should flat it by using flatMap
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const arrMap = arr.flatMap((it) => it);
console.log(arrMap);

How to make _lodash.zip with less code

Definition:Creates an array of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on.
Current Solution:
const zip = (...arr) => {
let maxLength = 0
let res = []
for (let el of arr) {
maxLength = Math.max(maxLength, el.length)
}
for (let j = 0; j < maxLength; j++) {
const foo = []
for (let n of arr) {
foo.push(n[j])
}
res.push(foo)
}
return res
}
Test Case:
test(('zip', () => {
expect(zip([1, 2], [4, 5], [9, 1])).toEqual([[1, 4, 9], [2, 5, 1]])
}
test('zip', () => {
expect(zip([1, 2, 3], [4, 5, 6])).toEqual([[1, 4], [2, 5], [3, 6]])
})
test('zip', () => {
expect(zip([1, 2], [], [3, 4, 5])).toEqual([
[1, undefined, 3],
[2, undefined, 4],
[undefined, undefined, 5],
])
})
I want to get a better way to achieve zip, current solution is ugly
See Destructuring Assignment and Array.prototype.map for more info.
// Proof.
const zip = (...args) => [...new Array(Math.max(...args.map(arr => arr.length)))].map((x, i) => args.map((y) => y[i]))
// Proof.
console.log(zip([1, 2], [4, 5], [9, 1])) // [[1, 4, 9], [2, 5, 1]]
console.log(zip([1, 2, 3], [4, 5, 6])) // [[1, 4], [2, 5], [3, 6]]
console.log(zip([1, 2], [], [3, 4, 5])) // [[1, undefined, 3], [2, undefined, 4], [undefined, undefined, 5]]

Get item what's not on the 2nd, 3rd arrays - JS

I am trying to create a function that will get the items that cannot be seen on the 2nd or 3rd and upcoming arrays passed within the function.
Right now my function gets only the similar items. How can I make it get the difference (w/c are the items that doesn't exist to the 2nd and 3rd and proceeding arrays.
const callM = function(arrays) {
arrays = Array.prototype.slice.call(arguments);
let result = [];
for(let i = 1; i < arrays.length; i++){
for(let x = 0; x < arrays[i].length; x++){
if(arrays[0].includes(arrays[i][x])){
result.push(arrays[i][x]);
}
}
}
return result;
};
console.log(callM([1, 2, 3, 4, 5], [5, 2, 10])); // -> must be [1, 3, 4]
console.log(callM([1, 2, 3, 4, 5], [5, 2, 10], [7, 1, 8])); // -> must be [3,4]
The logic right now is a bit off as it gets the opposite. How do i fix this?
Also is there a way to do this using Higher Order functions such as reduce or filter?
Thanks!
I'd think about this differently. As the difference between two sets: array 0 and array 1...n
To get array 0, just shift it off the top
const arr0 = arrays.shift()
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
This removes the first array from arrays
Next we combine the remaining arrays
const arrN = arrays.reduce(function(prev, curr) {
return prev.concat(curr)
})
Ref: http://www.jstips.co/en/javascript/flattening-multidimensional-arrays-in-javascript/
Unneeded, handled by includes as mentioned by #Phil
Next filter duplicates from arrN by comparing with itself
const unique = arrN.filter(function(elem, index, self) {
return index == self.indexOf(elem);
})
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Next filter with includes to find the difference (or union)
const diff = arr0.filter(function(item) {
return !arrN.includes(item))
}
Full snippet:
function callM(arrays) {
const arr0 = arrays.shift()
const arrN = arrays.reduce(function(prev, curr) {
return prev.concat(curr)
})
//const unique = arrN.filter(function(elem, index, self) {
// return index == self.indexOf(elem)
//})
return arr0.filter(function(item) {
return !arrN.includes(item)
})
}
console.log(callM([[1, 2, 3, 4, 5], [5, 2, 10]]))
console.log(callM([[1, 2, 3, 4, 5], [5, 2, 10], [7, 1, 8]]))
of course ES6 would be easier. ;)
const callM = (first, ...rest) => {
const arrays = [].concat(...rest)
return first.filter(item => !arrays.includes(item))
}
console.log(callM([1, 2, 3, 4, 5], [5, 2, 10]))
console.log(callM([1, 2, 3, 4, 5], [5, 2, 10], [7, 1, 8]))
A short solution for small and medium sized arrays:
// Return elements in array but not in filters:
function difference(array, ...filters) {
return array.filter(el => !filters.some(filter => filter.includes(el)));
}
// Example:
console.log(difference([1, 2, 3, 4, 5], [5, 2, 10])); // [1, 3, 4]
console.log(difference([1, 2, 3, 4, 5], [5, 1, 10], [7, 2, 8])); // [3, 4]
For large inputs, consider creating a Set from all filters and filtering in linear time using set.has(el).
In order to fix your implementation, you could label the outer for-loop and continue from there whenever a filter contains one of the array elements. Only when all filters pass without match, you push the array element into the result:
// Return elements in array but not in filters:
function difference(array, ...filters) {
const result = [];
loop: for (const el of array) {
for (const filter of filters) {
if (filter.includes(el)) continue loop;
}
result.push(el);
}
return result;
}
// Example:
console.log(difference([1, 2, 3, 4, 5], [5, 2, 10])); // [1, 3, 4]
console.log(difference([1, 2, 3, 4, 5], [5, 2, 10], [7, 1, 8])); // [3,4]
If you're willing to use Underscore, you can do this in one line of code:
console.log(_.difference([1, 2, 3, 4, 5], [5, 2, 10], [7, 1, 8]))
https://jsfiddle.net/o1zuaa6m/
You can use array#reduce to create object lookup of all the other array excluding the first array. Then use array#filter to get the values which are not present in the object lookup
var callM = (first, ...rest) => {
var combined = rest
.reduce((res,arr) => res.concat(arr))
.reduce((o, v) => {
o[v] = true;
return o;
},{});
return first
.filter(v => !combined[v]);
}
console.log(callM([1, 2, 3, 4, 5], [5, 2, 10])); // -> must be [1, 3, 4]
console.log(callM([1, 2, 3, 4, 5], [5, 2, 10], [7, 1, 8])); // -> must be [3,4]
The "proper" way to exclude values is usually to use a lookup hash set with the values to exclude:
const callM = (a, ...b) => (b = new Set(b.concat.apply(...b)), a.filter(v => !b.has(v)))
console.log(callM([1, 2, 3, 4, 5], [5, 2, 10])); // [1, 3, 4]
console.log(callM([1, 2, 3, 4, 5], [5, 2, 10], [7, 1, 8])); // [3, 4]

Filter intersection of arrays (Javascript)

I'm trying to write a function that finds arrays that are not common to both nested arrays. Also note the arrays will be pre-sorted.
var array1 = [ [1, 2, 3], [2, 3, 4] [5, 6, 7] ];
var array2 = [ [1, 2, 3], [2, 3, 4] [7, 8, 9] ];
For the above two arrays the function should return [5, 6, 7] and [7, 8, 9].
So far I've got:
function arrayIntersection(array1, array2) {
return array2.filter(function(values1) {
return array2.indexOf(values1) === -1;
});
};
But it doesn't seem to be working. I'm guessing the indexOf() isn't doing a compares correctly. I'm trying to avoid using ES6 or polyfills.
You can use the built in .every() and .filter() array methods to accomplish this task.
var array1 = [ [1, 2, 3], [2, 3, 4], [5, 6, 7] ];
var array2 = [ [1, 2, 3], [2, 3, 4], [7, 8, 9] ];
function compareArrays(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
} else {
return arr1.every(function(elem) {
return arr2.indexOf(elem) > -1;
});
}
}
function filterUnique(arr1, arr2) {
return arr1.filter(function(elem) {
return arr2.every(function(_elem) {
return !compareArrays(_elem, elem);
});
});
}
function filterIntersection(arr1, arr2) {
var uniqueToArr1 = filterUnique(arr1, arr2);
var uniqueToArr2 = filterUnique(arr2, arr1);
return [].concat(uniqueToArr1, uniqueToArr2);
}
console.log(filterIntersection(array1, array2));
First, you referenced the wrong array in your filter. To fix the comparison, you could turn the arrays to json. You will also need to run the filter against the second array and join the answers.:
var array1 = [ [1, 2, 3], [2, 3, 4], [5, 6, 7] ];
var array2 = [ [1, 2, 3], [2, 3, 4], [7, 8, 9] ];
function arrayIntersection(input1, input2) {
var input2NotInInput1 = input2.filter(function(values1) {
return input1.map(function(val) { return JSON.stringify(val); }).indexOf(JSON.stringify(values1)) === -1;
});
var input1NotInInput2 = input1.filter(function(values1) {
return input2.map(function(val) { return JSON.stringify(val); }).indexOf(JSON.stringify(values1)) === -1;
});
return input1NotInInput2 .concat( input2NotInInput1 );
};
console.log(arrayIntersection(array1, array2));
It's not a best option but it works
var ar1 = [
[1, 2, 3],
[2, 3, 4],
[5, 6, 7]
];
var ar2 = [
[1, 2, 3],
[2, 3, 4],
[7, 8, 9]
];
function arrayIntersection(array1, array2) {
return array2.filter(function(values1) {
return !array1.some(v => JSON.stringify(v) === JSON.stringify(values1));
});
};
var result = arrayIntersection(ar1, ar2);
console.log(result);

Categories