I am working on an array which is like this:
var arr = [
{floor: '1', id: '10165', label: 'Elutuba/Köök'},
{floor: '1', id: '10166', label: 'Tuba 1'},
{floor: '1', id: '10167', label: 'Vannituba'},
{floor: '2', id: '10167', label: 'Vannituba'}
];
Now i want to compare the floor items here. If all the floor value is same, then it should return true and if there are multiple values like '1' & '2' in this array, it should return false.
Here's what i have tried so far
var arr = [
{floor: '1', id: '10165', label: 'Elutuba/Köök'},
{floor: '1', id: '10166', label: 'Tuba 1'},
{floor: '1', id: '10167', label: 'Vannituba'},
{floor: '2', id: '10167', label: 'Vannituba'}
];
for (let i=0; i< arr.length; i++){
for (let j=1; j< arr.length; j++){
if( arr[i].floor !== arr[j].floor){
console.log('found');
}else{
console.log('Not found');
}
}
}
I know this is nowhere close to the solution. But i'm stuck.
An initial naive approach.
floor property of the first item using Destructuring assignment and rename it to firstFloorArray.prototype.every()
to check if all the items meet a certain criteriaconst allSameFloors = (array = []) => {
const [{
floor: firstFloor
}] = array;
return array.every(({
floor
}) => floor === firstFloor);
};
console.log(
allSameFloors(
[{
floor: '1',
id: '10165',
label: 'Elutuba/Köök'
},
{
floor: '1',
id: '10166',
label: 'Tuba 1'
},
{
floor: '1',
id: '10167',
label: 'Vannituba'
},
{
floor: '2',
id: '10167',
label: 'Vannituba'
}
]
)
);
console.log(
allSameFloors(
[{
floor: '1',
id: '10165',
label: 'Elutuba/Köök'
},
{
floor: '1',
id: '10166',
label: 'Tuba 1'
},
{
floor: '1',
id: '10167',
label: 'Vannituba'
},
{
floor: '1',
id: '10167',
label: 'Vannituba'
}
]
)
);
There more than likely is a better way of doing this but here is a quick solution.
function FloorSameValue(arr){
values = [];
for (obj of arr){
if (!values.includes(obj.floor)){
values.push(obj.floor);
}
}
return values.length === 1;
}
var arr = [
{floor: '1', id: '10165', label: 'Elutuba/Köök'},
{floor: '1', id: '10166', label: 'Tuba 1'},
{floor: '1', id: '10167', label: 'Vannituba'},
{floor: '2', id: '10167', label: 'Vannituba'}
];
console.log(FloorSameValue(arr))
//false
for( var i = 0 ; i < arr.length;i++)
{
var myval = arr[i].floor;
for (var j = i+1 ; j < arr.length ; j++)
{
if (arr[i].floor !== arr[j].floor)
{
alert("false");
}
}
}
enter code here