【问题标题】:How can the first element be compared to the rest of the elements and the second element to the rest of the elements and the same repetition如何将第一个元素与其余元素进行比较,将第二个元素与其余元素进行比较以及相同的重复
【发布时间】:2020-12-12 15:34:49
【问题描述】:

我想比较同一个数组中的元素来得到这个结果

      let arr = ['one','two','three','four'];
      arr.forEach((ele, i, ar)=>{
      console.log(ele, i, ar)
      for(let item = i; item< ar.length; item++ ){
        console.log (ele, ar[item])
      }
    })
    'one' => 'two',
    'one' => 'three',
    'one' => 'four',
    'two' => 'three',
    'two' => 'four',
    'three' => 'four'.

【问题讨论】:

标签: javascript arrays angular for-loop string-literals


【解决方案1】:

你可以使用两个for循环,让第二个循环从第一个循环的索引+1开始:

let arr = ['one','two','three','four'];


for(let i=0; i< arr.length; i++){
  for(j=i+1; j<arr.length; j++){
    console.log(arr[i],' => ', arr[j]);
  }
  }

【讨论】:

  • 感谢您的回复我想要这个结果,同时删除重复的结果
  • 我不确定我是否理解。你能更好地解释你需要什么吗?
  • 一=>一一=>二一=>三一=>四二=>二二=>三二=>四三=>三三=>四四=>四-- ----------------------- 我要删除 ----------- -------- 一 => 一、二 => 二三 => 三四 => 四
  • 我更新了答案,现在应该是你想要的了
【解决方案2】:

使用flatMapslice

let arr = ["one", "two", "three", "four"];

const res = arr.flatMap((x, i) => arr.slice(i + 1).map(y => `${x} => ${y}`));

console.log(res)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多