I have an array
const array = [[1, 2], [3, 3]]; arr.forEach(el => {
if (el[0] === el[1]) {return true}
})
CodePudding user response:
You should should every
function
const arr = [[1, 2], [3, 3]];
const b = arr.every(el => el[0] === el[1]);
console.log(b); // false
CodePudding user response:
This should get the desired result. Just change console.log(true) to whatever you would like to do if they equal each other. This will work on any length of array.
const array = [
[1, 2],
[3, 3],
];
array.forEach((el) => {
if (el[0] === el[el.length - 1]) {
console.log(true);
}
});
CodePudding user response:
map
over the array to produce a new array of true/false values determined on whether the elements match.
const out = [[1, 2], [3, 3]].map(arr => {
return arr[0] === arr[1];
});
console.log(out);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
There is no point in return true in a forEach
I assume you mean this:
const testArr = arr => arr[0] === arr[arr.length-1]; // test first and last
const array = [[1, 2], [3, 3]];
const testResults = array.map(el => testArr(el)); // map the results
console.log(testResults)
// filter:
const same = array.filter(el => testArr(el)); // FIND the array that has same first and last
console.log(same.flat())
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>