我的价值是这样的:
var x = "market^price^cost";
var y = "market^price"; //y could be anywhere in the x
var z = x + "+" + y //I want this to be `"market^price^cost"`
console.log(x + "+" + y) //"market^price^cost+market^price"
只有当X
的值为y
时,此逻辑才有效,如果日志值不正常,我们应该得到整个字符串,y
的值的顺序可以与众不同。
答案 0 :(得分:0)
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
Array.prototype.uniqueMerge = function( a ) {
for ( var nonDuplicates = [], i = 0, l = a.length; i<l; ++i ) {
if ( this.indexOf( a[i] ) === -1 ) {
nonDuplicates.push( a[i] );
}
}
return this.concat( nonDuplicates )
};
function myFunction() {
var x = "market^price^cost";
var y = "market^price";
var xS = x.split("^");
var yS = y.split("^");
var res = xS.uniqueMerge(yS).join("^");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
答案 1 :(得分:0)
你可以使用lodash Array _.uniq()函数
return _.uniq((x+'^'+y).split('^')).join('^');
或者您可以编写一个函数来删除Array中的重复数据;
function removeSame(arr) {
for(let i = 0;i<arr.length;i++) {
if(arr.indexOf(arr[i]) != i) {
arr.splice(i,1);
i--;
}
}
return arr;
}
return removeSame((x+'^'+y).split('^')).join('^')