检查循环中的前一个标识是否与当前标识不同。

huangapple go评论61阅读模式
英文:

Check if prev id in a loop is not same as current

问题

如何检查当前的id是否与前一个id相同?

英文:

Lets say there is an array of objects

array = [
  { id : 1, name: 'aaa' },
  { id : 1, name: 'asd' },
  { id : 2, name: 'asd' }
]

in a loop eg

array.forEach(a => {
  currentId = a.id 
});

how to check if current id is same or not as prev id ?

答案1

得分: 1

你可以使用索引来获取前一个条目:

array = [{ id : 1, name : 'aaa' }, { id : 1, name: 'asd' }, {id : 2, name : 'asd'} ]

array.forEach((a, index) =>{
  let currentId = a.id

  // Check if previous exists (Index will be 0 on first run)
  if (index) {
    let previousId = array[index - 1].id
    // If exists we can check it
    console.log(currentId === previousId)
  }
})
英文:

You can use the index to get the previous entry:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

array = [{ id : 1, name : &#39;aaa&#39; }, { id : 1, name: &#39;asd&#39; }, {id : 2, name : &#39;asd&#39;} ]

array.forEach((a, index) =&gt;{
  let currentId = a.id

  // Check if previous exists (Index will be 0 on first run)
  if (index) {
    let previousId = array[index - 1].id
    // If exists we can check it
    console.log(currentId === previousId)
  }
})

<!-- end snippet -->

答案2

得分: 1

你可以使用 reduce 如下:

const array = [{
  id: 1,
  name: 'aaa'
}, {
  id: 1,
  name: 'bbb'
}, {
  id: 2,
  name: 'cccc'
},
{
  id:2,
  name:'ddd'
}];

array.reduce((prev, next) => {
    if (prev.id === next.id) {
      console.log(`${prev.name} 有相同的 id:${next.name}`);
    }
    return next;
});
英文:

You can use reduce like:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const array = [{
  id: 1,
  name: &#39;aaa&#39;
}, {
  id: 1,
  name: &#39;bbb&#39;
}, {
  id: 2,
  name: &#39;cccc&#39;
},
{
  id:2,
  name:&#39;ddd&#39;
}];

array.reduce((prev, next) =&gt; {
    if (prev.id === next.id) {
      console.log(`${prev.name} has same id of ${next.name}`);
    }
    return next;
});

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月5日 19:41:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76406061.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定