![](/img/trans.png)
[英]How to get all combinations of a string by removing 4 characters each time?
[英]How to get all combinations of array elements after removing each element
我想在刪除每個元素后獲得所有數組元素的所有組合
例如:
輸入: [6,5,3,4]
輸出應為: [[5,3,4],[6,3,4],[6,5,4],[6,5,3]]
不使用任何庫
我在這段代碼中工作,但沒有輸出正確的結果
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]);
您可以通過迭代給定數組和映射數組來使用嵌套方法,而不需要外部索引的元素。
var array = [6, 5, 3, 4], result = array.map((_, i) => array.filter((_, j) => i !== j)); console.log(result);
在您的代碼中,您需要檢查過濾器回調的索引而不是值。
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]);
簡單的forEach
+ filter
:
只需比較索引即可過濾下一個元素。
var result = []; var array = [6,5,3,4]; array.forEach((_, i) => result.push(array.filter((_, j) => i !== j))); console.log(result);
無需復雜化,其實就是一個簡單的算法。
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.