我需要像第一个结果一样组合string1
和string2
。之后,我只想要唯一的信息,没有"颜色类型信息"。如第二个结果
string1 = "Green | Green | Red | Orange | Blue | Cut | Yellow | Yellow"
string2 = "Color | Color | Color | Color | Color | Technical | Color | Color"
第一个结果:string3 = Green Color | Green Color | Red Color | Orange Color | Blue Color | Cut Technical | Yellow Color | Yellow Color
第二个结果:string4 = 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 = "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'
如果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);