繁体   English   中英

Java 脚本组合字符串/数组

[英]Java Script combine strings/arrays

我需要像第一个结果一样组合string1string2 之后,我只想要唯一的信息,没有像第二个结果那样的“颜色类型信息”。

string1 = "Green | Green | Red | Orange | Blue | Cut | Yellow | Yellow"

string2 = "Color | Color | Color | Color | Color | Technical | Color | Color"

第一个结果: string3 = 绿色 | 绿色 | 红色 | 橙色 | 蓝色 | 切割技术 | 黄色 | 黄色

第二个结果: string4 = 绿色 | 红色 | 橙色 | 蓝色 | 切 | 黄色

你可以这样做:

string1 = "Green | Green | Red | Orange | Blue | Cut | Yellow | Yellow"

split_text = string1.split("|")
Result = Array.from(new Set(split_text.map(x => x.trim()))).join('|')
//'Green|Red|Orange|Blue|Cut|Yellow'

你可以做这样的事情

 const string1 = 'Green | Green | Red | Orange | Blue | Cut | Yellow | Yellow' const string2 = 'Color | Color | Color | Color | Color | Technical | Color | Color' const [arr1, arr2] = [string1, string2].map(s => s.split(' | ')) const string3 = arr1.map((s, i) => `${s} ${arr2[i]}`).join(' | ') const string4 = [...new Set(arr1)].join(' | ') console.log({string3, string4})

 const string1 = 'Green | Green | Red | Orange | Blue | Cut | Yellow | Yellow' const string2 = 'Color | Color | Color | Color | Color | Technical | Color | Color' const combine = (str1, str2, div = ' | ') => { str1 = str1.split(div) str2 = str2.split(div) return str1.map((word, i) => `${word} ${str2[i]}`).join(div) } const unique = str1 => [...new Set(str1.split(' | '))].join(' | ') const firstResult = `Green Color | Green Color | Red Color | Orange Color | Blue Color | Cut Technical | Yellow Color | Yellow Color` const secondResult = 'Green | Red | Orange | Blue | Cut | Yellow' console.log(firstResult === combine(string1, string2)) console.log(secondResult === unique(string1))

如果 string1 和 string2 信息长度不同

 var string1 = "Green | Green | Red | Orange | Blue | Cut | Yellow | Yellow"; var string2 = "Color | Color | Color | Color | Color | Technical | Color | Color"; var firstlength=string1.split("|").length; var secondlength=string2.split("|").length; var maxilength=firstlength; if(secondlength>firstlength) maxilength=secondlength; var string1split=string1.split("|"); var string2split=string2.split("|"); var concatstr=""; for(var i=0;i<maxilength;i++){ if(string1split.length>i){ concatstr+=string1split[i]; } if(string2split.length>i){ concatstr+=string2split[i]; } if(i<maxilength-1){ concatstr+="|"; } } console.log(concatstr); function onlyUnique(value, index, self) { return self.indexOf(value) === index; } for(var i=0;i<string1split.length;i++){ string1split[i]=string1split[i].trim(); } var uniquecolors=string1split.filter(onlyUnique); var uniquecolorsstring=uniquecolors.join(" | "); console.log(uniquecolorsstring);

暂无
暂无

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

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