How to convert an array to multiple array - javascript

I have an array abc = [1, 2, 3].
How can i convert it to multiple arrays: [1, 2] , [1, 3], [2, 3]
Note: If abc have n items, we will convert to n*(n-1) arrays

you could do something like this:
const combinations = arr =>
arr.flatMap((elX, indexX) =>
arr
.filter((_, indexY) => indexY == indexX)
.map(elY => [elX, elY])
)
the result will be n*(n-1) so for [1,2,3] = [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]

Looks like you want to list all kind of combination to be made from original array
you can run code below in console to check if it fits your needs
Note that in code below, i use filter to avoid same value in the same array group
Sorry for my bad english
let arr = [1, 2, 3];
arr = arr.map((currentValue, index, arr)=>{
return arr.filter((val2, idx2) => val2 !== currentValue);
});
document.write(JSON.stringify(arr,null,4));
Edit: i know the question wants 6 arrays, this code above is following the example he gave... This is alternative answer if what he really meant was to find every single unique combination (without mirror effect)

Related

Compare two arrays of integers and return an array with all matches

I currently have two arrays with a bunch of ids. I want to compare the two arrays to see what ids match, then return an array with only the matching ids. I've tried multiple approaches, but nothing seems to work so far. This is what I've done:
const filteredIdArray = array1.filter((item) =>
array2(item)
);
const filteredIdArray = array1.filter(
(item) => array2.indexOf(item) !== -1
);
Both attempts were pulled from other examples, and neither is working. I did make sure that my array1 and array2 were actually arrays not objects. Is there something I'm missing here?
Rephrasing, this is array intersection. A terse, readable, quick (1 pass through each array) is (sort of like this)...
const intersect = (a, b) => {
const setB = new Set(b);
return a.filter(el => setB.has(el));
}
console.log(intersect([1,2,3,4], [3,4,5,6]))
There's ambiguity in the question about whether we're aiming for unique matches. This idea returns all matches, including duplicates. To eliminate those, run the result through a set once more. [...new Set(resultWithDups)]
I think in the first approach it should be array2.includes.
const filteredIdArray = array1.filter((item) => array2.includes(item))
Use a intermediate hash object to hold id's as its key.
That would make it easier to find "duplicates" and push to a result.
arr1 = [1, 2, 3, 4, 0]
arr2 = [3, 4, 5, 6, 0]
result = []
hash = {}
arr1.forEach(item => hash[item] = true)
arr2.forEach(item => hash[item] === true && result.push(item))
console.log(result)
You can use Array#filter and Array#includes methods as follows:
const
arr1 = [2,5,6,8,9,10],
arr2 = [3,4,7,6,8,11],
output = arr1.filter(n => arr2.includes(n));
console.log( output );
Also .....
Your second option should work:
const
arr1 = [2,5,6,8,9,10],
arr2 = [3,4,7,6,8,11],
output = arr1.filter(n => arr2.indexOf(n) !== -1);
console.log( output );

Javascript checking only the first item of an array

I have an array of arrays, i.e. [ [1,2], [1,3] ] and I want to check if is there any 1 as the first element of a subarray. It doesn't matter if it is a [1,2] or [1,3]. I'm interested only in the 1's existence. Sure I could use some loops to do this, but I wonder if is there an elegant "built-in" way to do this in js, something like:
arr.includes([1, _]) // returns true if is there any 1 as first element of an array
some is something you are looking for.
Code example:
const data = [[1, 3], [1, 5]]
const res = data.some( ([a, _]) => a === 1 ) // less elegant alternative:
// .some(e => e[0] === 1)
console.log(res)

filter and includes showing error message

can someone please explain to me why this is not working?
const numbers = [1, 2, 3, 4, 5];
const filtered = numbers.filter((num) => num.includes(1));
console.log(filtered);
I am getting this message saying num.includes is not a function.
.includes exists for two prototypes, Array.prototype.includes() and String.prototype.includes(), your array elements are of type number which has no such method
.includes() only works on strings or arrays. You are calling on a number. You want const filtered = numbers.filter((num) => num === 1)
var numbers = [1, 2, 3, 4, 5];
numbers=numbers.map(String);//changes elements to string
const filtered = numbers.filter((num) => num.includes(1));
console.log(filtered);
should fix the problem

How would one add items to the beginning of an array with Lodash?

I've been searching for a while to add items to the beginning of an array with lodash. Unfortunately I can't seem to find anything other than lodash concat (to the end of the array). The docs don't seem to say anything about it either.
I got the following code:
const [collection, setCollection] = useState({
foo: [1, 2, 3]
});
const addToCollection = (key, items) => {
setCollection(prevCollection => ({
...prevCollection,
[key]: _.concat(prevCollection[key] || [], items)
}));
};
But this concats all the items to the end. I don't want to sort them every time because that uses unnessecary processing power, I would much rather just add them to the beginning because the API always pushes the items already sorted
How would I accomplish this:
addToCollection('foo', [4, 5, 6]);
console.log(collection['foo']) // [4, 5, 6, 1, 2, 3];
Instead of what is happening now:
addToCollection('foo', [4, 5, 6]);
console.log(collection['foo']) // [1, 2, 3, 4, 5, 6];
Try swapping the arguments:
_.concat(items, prevCollection[key] || [])
Or vanilla JS is pretty easy too:
Collection.unshift('addMe', var, 'otherString' )
https://www.w3schools.com/jsref/jsref_unshift.asp#:~:text=The%20unshift()%20method%20adds,use%20the%20push()%20method.
I know you asked for lodash but I figured this is a good thing to be aware of too :)
EDIT:
To clarify, this works the same whether you're pushing defined vars, string, arrays, objects or whatever:
let yourArray = [1,2,3];
let pushArray = [1,2,3,4];
let anotherArray = [7,8,9];
yourArray.unshift(pushArray, anotherArray);
will push "pushArray" and "anotherArray" to the begining of "yourArray" so it's values will look like this:
[[1,2,3,4], [7,8,9], 1,2,3]
Happy Coding!

How to combine array within another array using javascript or jquery?

I have an array named arr and within that array, I have another array.My question is, how to combine this two array?
var arr=["1","2","[3,4]","5"]
My output should be like this:
1,2,3,4,5
Thanks in advance!
You could use spread syntax ... with map and JSON.parse methods.
var arr = ["1","2","[3,4]","5"]
var result = [].concat(...arr.map(e => JSON.parse(e)))
console.log(...result)
Considering that you have an actual array and not a string you can flatten like this
var arr=["1","2",["3","4"],"5"]
var flat = [].concat(...arr)
console.log(flat)
You can change it to string and further replace the square brackets using replace(/[\[|\]]/g,''):
var arr=["1","2","[3,4]","5"];
var res = arr.toString().replace(/[\[|\]]/g,'');
console.log(res);
If the question is how to flat an array like this [1,2,[3,4],5] or this [1,[2,[[3,4],5]]] into this[ 1, 2, 3, 4, 5 ] here a pretty general and short solution:
var arr = [1, [2, [[3, 4], 5]]];
var newArr = JSON.parse("[" + JSON.stringify(arr).replace(/\[|\]/g, "") + "]");
console.log(newArr)
Or .flat if browser supports it:
var arr = [1, 2, [3, 4, [5, 6]]];
arr.flat();
console.log(arr)

Categories

Resources