简体   繁体   English

如何在JS中获得不同顺序的所有组合?

[英]How to get all combinations with different order in JS?

I've got an array with six items in it.我有一个包含六个项目的数组。

['orange', 'strawberry', 'melon','apple','banana','coconut']

I was able to get many combinations but the, unfortunately, my script isn't able to set eg the last item to the front so that I have really all combinations.我能够获得许多组合,但不幸的是,我的脚本无法将最后一项设置为前面,因此我真的拥有所有组合。

If you look at the end of the following output, you see that coconut is always at the end but it should also be at the first place, second place etc.如果您查看以下输出的末尾,您会看到椰子总是在末尾,但它也应该在第一、第二等位置。

(It is intended that there are no spaces between the items) (旨在项目之间没有空格)

orange
strawberry
orangestrawberry
melon
orangemelon
strawberrymelon
orangestrawberrymelon
apple
orangeapple
strawberryapple
orangestrawberryapple
melonapple
orangemelonapple
strawberrymelonapple
orangestrawberrymelonapple
banana
orangebanana
strawberrybanana
orangestrawberrybanana
melonbanana
orangemelonbanana
strawberrymelonbanana
orangestrawberrymelonbanana
applebanana
orangeapplebanana
strawberryapplebanana
orangestrawberryapplebanana
melonapplebanana
orangemelonapplebanana
strawberrymelonapplebanana
orangestrawberrymelonapplebanana
coconut
orangecoconut
strawberrycoconut
orangestrawberrycoconut
meloncoconut
orangemeloncoconut
strawberrymeloncoconut
orangestrawberrymeloncoconut
applecoconut
orangeapplecoconut
strawberryapplecoconut
orangestrawberryapplecoconut
melonapplecoconut
orangemelonapplecoconut
strawberrymelonapplecoconut
orangestrawberrymelonapplecoconut
bananacoconut
orangebananacoconut
strawberrybananacoconut
orangestrawberrybananacoconut
melonbananacoconut
orangemelonbananacoconut
strawberrymelonbananacoconut
orangestrawberrymelonbananacoconut
applebananacoconut
orangeapplebananacoconut
strawberryapplebananacoconut
orangestrawberryapplebananacoconut
melonapplebananacoconut
orangemelonapplebananacoconut
strawberrymelonapplebananacoconut
orangestrawberrymelonapplebananacoconut

You may have a look to this:你可以看看这个:

 ab a ab b ba

 abc a ab abc ac acb b ba bac bc bca c ca cab cb cba

The above shows, that you can take every item and call the function again with the array without the used item.上面显示,您可以获取每个项目并使用数组再次调用该函数,而无需使用该项目。 As result, you get an array with any combination.结果,您会得到一个任意组合的数组。

 function getCombinations(array) { var i, result = []; for (i = 0; i < array.length; i++) { result.push( array[i], ...getCombinations(array.filter((_, j) => i !== j)).map(v => array[i] + v) ); } return result; } var array = ['orange', 'strawberry', 'melon', 'apple', 'banana', 'coconut']; console.log(getCombinations(array));
 .as-console-wrapper { max-height: 100% !important; top: 0; }

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

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