I want to get all combinations of all array elements after removing each element
For example:
input: [6,5,3,4]
output should be: [[5,3,4],[6,3,4],[6,5,4],[6,5,3]]
Without using any libraries
I worked in this code but did not output the right results
var arrs = [[]]; function doIt(arr) { for (var i = 0; i < arr.length; i++) { arrs[i] = arr.filter(function (item) { return item != i }); } console.log(JSON.stringify(arrs)); } doIt([4, 3, 1]);
You could use a nested approach by iterating the given array and map arrays without the element of the outer index.
var array = [6, 5, 3, 4], result = array.map((_, i) => array.filter((_, j) => i !== j)); console.log(result);
In your code, you need to check against the index of the filter callback instead of the value.
var arrs = [[]]; function doIt(arr) { for (var i = 0; i < arr.length; i++) { arrs[i] = arr.filter(function (item, j) { // ^ use index instead of value return j != i; // ^ here }); } console.log(arrs); } doIt([4, 3, 1]);
Simple forEach
+ filter
:
Just compare the indexes to filter the next element.
var result = []; var array = [6,5,3,4]; array.forEach((_, i) => result.push(array.filter((_, j) => i !== j))); console.log(result);
No need to complex it, it's realy a simple algorithm.
var input = [6,5,3,4]; var output = []; for (i = 0; i < input.length; ++i) { temp = []; for (j = 0 ; j < input.length; ++j) { if (i != j) temp.push(input[j]); } output.push(temp); } console.log(output);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.