当前位置:网站首页>JS merge multiple string arrays to maintain the original order and remove duplicates

JS merge multiple string arrays to maintain the original order and remove duplicates

2022-06-13 02:52:00 Programming Bruce Lee

Realization effect

Merge any string array , And keep the original order of strings for merging and de duplication , The effect is shown in the figure :
 Insert picture description here

The implementation code is as follows

 First, simply implement the merging between two string arrays , recycling js The implementation of recursive call with variable parameters of n A combination of string arrays 
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title> Dragon brother </title>
</head>

<body>
    <script type="text/javascript"> /** *  Merge in order n Array of strings and remove duplicates  * @param {...any} strArrys //  Array of multiple character strings  */ function mergeStrArrays(...strArrys) {
       if (!strArrys) {
       return []; } //  Recursive export  if (strArrys.length < 2) {
       return strArrys[0] ? strArrys[0] : []; } //  Recursively call  return mergeStrArrays(mergeStrArray(strArrys.pop(), strArrys.pop()), ...strArrys); } /** *  Merge two string arrays in order and remove duplicates  * @param {Array} strArry1  Array of strings  * @param {Array} strArry2  Array of strings  * @returns */ function mergeStrArray(strArry1, strArry2) {
       if (strArry2.length > strArry1.length) {
       //  Guarantee strArry1 Than strArry2 Long  let strT = strArry2; strArry2 = strArry1; strArry1 = strT; } for (let i = 0; i < strArry1.length; i++) {
       if (strArry2[i] === undefined) {
       break; } //  If the corresponding position str1 Elements and str2 Elements are different and str1 There is no such element in the array , Add... At this location str2 Elements  if (strArry1[i] !== strArry2[i]) {
       let j = 0; for (j; j < strArry1.length; j++) {
       if (strArry1[j] === strArry2[i]) {
       break; } } if (j >= strArry1.length) {
       strArry1.splice(i, 0, strArry2[i]); } } } return strArry1; } let str1 = ["aaa", "bbb", "ccc", "ddd", "eee"] let str2 = ["bbb", "ccc", "eee", "ffff"] let str3 = ["bbb", "ccc", "mmm", "ggg"] console.log(" The three string arrays are :"); console.log(str1); console.log(str2); console.log(str3); console.log(" After the merger :"); console.log(mergeStrArrays(str1, str2, str3)); </script>
</body>
</html>
原网站

版权声明
本文为[Programming Bruce Lee]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280536144844.html