Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用reduce函数比较两个字符串中的符号_Javascript_Arrays_Loops_Ecmascript 6 - Fatal编程技术网

Javascript 使用reduce函数比较两个字符串中的符号

Javascript 使用reduce函数比较两个字符串中的符号,javascript,arrays,loops,ecmascript-6,Javascript,Arrays,Loops,Ecmascript 6,我试着比较数组中两个相等符号或字符的字符串,这段代码可以工作,但是如果数组中有两个以上的字符串,如何在ES6中使用reduce方法实现它。如果数组第一个元素中的字符串包含数组第二个元素中字符串的所有字母,则需要返回true。但是如果数组中有2个以上的元素,如何创建更灵活的函数呢 function mutation(arr) { var arr2 = arr.map(item => item.toLowerCase().split('')); for (i=0;i&l

我试着比较数组中两个相等符号或字符的字符串,这段代码可以工作,但是如果数组中有两个以上的字符串,如何在ES6中使用reduce方法实现它。如果数组第一个元素中的字符串包含数组第二个元素中字符串的所有字母,则需要返回true。但是如果数组中有2个以上的元素,如何创建更灵活的函数呢

function mutation(arr) {
      var arr2 = arr.map(item => item.toLowerCase().split(''));
      for (i=0;i<arr2[1].length;i++) {
        if (arr2[0].indexOf(arr2[1][i]) < 0)
          return false;
      }

      return true;
    }

    mutation(["hello", "hey"]);
功能突变(arr){
var arr2=arr.map(item=>item.toLowerCase().split(“”));

对于(i=0;i@Palaniichuk),我认为您的原始算法非常可靠。为了处理您的请求,我能够创建一个使用reduce的解决方案

我有一个问题要问你。如果数组的大小增加,字符串将如何计算

我之所以问这个问题,是因为使用像这样的帮助函数可能会帮助你扩展这个算法。当然,这一切都取决于输入是如何变化的。输入是如何计算的

function makeStr(string) {
  const reducer = string.split('').reduce((a, b) => {
    a[b] = a[b] + 1 || 1;
    return a;
  }, {});
  return Object.keys(reducer).sort().join('');
}

function secondMutation(arr) {
  const array = [...arr].map(makeStr);
    return array[0].includes(array[1]);
};

console.log(secondMutation(["hello", "hell"]));

为什么您要获取一个数组,然后执行
arr2
并按索引引用它?为什么该函数不直接获取
第一个
第二个
?您的代码只是
函数突变(第一,第二){first=first.toLowerCase();second=second.toLowerCase();返回array.from(second)。every(c=>first.includes(c));}
。如果必须…
函数变异(first,second){first=first.toLowerCase();second=second.toLowerCase();返回数组.from(second).reduce((p,c)=>p&&first.includes(c),true);}
如果数组第一个元素中的字符串包含数组第二个元素中字符串的所有字母,我需要返回true。但是如果数组中有2个以上的元素,如何创建更灵活的函数。@PalaniichukDmytro好吧,如果你写的是我上面写的版本,那么你就永远调用它我是其中一对。