简体   繁体   English

删除每个元素后如何获取数组元素的所有组合

[英]How to get all combinations of array elements after removing each element

I want to get all combinations of all array elements after removing each element我想在删除每个元素后获得所有数组元素的所有组合

For example:例如:

input: [6,5,3,4]输入: [6,5,3,4]

output should be: [[5,3,4],[6,3,4],[6,5,4],[6,5,3]]输出应为: [[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 :简单的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM