英文:
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 : '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)
}
})
<!-- 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: '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} has same id of ${next.name}`);
}
return next;
});
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论