There is an array of objects. A table is drawn on the base of the array. 
The task is to get the first and last id values for the color segment by clicking on the cell. If you make a click as shown in the picture, then the values "c9" and "d31" must be obtained. Also for any other segment. I tried to define an element in the array by clicking, and from it to use while back and forth, until the color of the next cell matches the current one. Then we write down id. But something does not go out. That does not work, then the eternal cycle begins. Maybe while generally a bad idea. I would appreciate the help
let arr = [ { id: 'm2c', color: 'yellow' }, { id: 'd1b', color: 'red' }, { id: 'd6', color: 'red' }, { id: 'd3', color: 'red' }, { id: 'd4', color: 'red' }, { id: 'd5', color: 'yellow' }, { id: 'd6', color: 'yellow' }, { id: 'd7', color: 'yellow' }, { id: 'v1', color: 'yellow' }, { id: 'c9', color: 'red' }, { id: 'd1k', color: 'red' }, { id: 'd92', color: 'red' }, { id: 'd12', color: 'red' }, { id: 'd31', color: 'red' }, { id: 'd14', color: 'yellow' }, { id: 'd12', color: 'yellow' }, { id: 'd45', color: 'yellow' }, { id: 'd3', color: 'yellow' }, { id: 'd00', color: 'yellow' }, { id: 'd3o', color: 'yellow' }, ]; let ul = document.createElement('ul'); let startId = document.createElement('span'); let endId = document.createElement('span'); arr.forEach(function (item) { let li = document.createElement('li'); li.style.backgroundColor = item.color; li.innerHTML = item.id; ul.appendChild(li); }); document.getElementById('container').appendChild(ul); document.getElementById('container').appendChild(startId ); document.getElementById('container').appendChild(ul); document.querySelector('ul').addEventListener('click', e => { let content = e.target.innerHTML; let startIdValue; let endIdValue; arr.forEach(function (item, i, arr) { if (item.id === content) { while (arr[i--]) { if (arr[i - 1].color !== item.color) { startIdValue = item.id; return } } while (arr[i++]) { if (arr[i + 1].color !== item.color) { endIdValue = item.id; return } } } }); }); ul { width: 1000px; padding-left: 0; margin-left: 0; display: flex; } li { width: 50px; height: 50px; list-style-type: none; border: 1px solid #ccc; } <div id="container"> </div> 