let s = i[0] for (let x = 2; x < i.length; x++) { if (i[x].indexOf(s) > -1) { for (let c of i[x].split(' ')) { if (c !== s) { s = c break } } } } console.log(s)