I have an array object called members?.admins
. I want to create an array of numbers based on the length of members?.admins
.
As an exception, if the length of members?.admins is 1 to 5, [1] should be given as the default value. That is, the default value must be unconditionally [1]
.
If the number of members?.admins
is 5, I want to make [1]
in numbers, and if there are 10
, I want to make [1,2]
. Also, if there are 11
, it should be [1,2]
At this time, I want to use useEffect
to setNumbers on the first render to create an array of numbers in numbers.
How can I do that?
const members?.admins = [{memberId:"21",name:"jack21"},{memberId:"20",name:"jack20"},{memberId:"14",name:"jack14"},{memberId:"13",name:"jack13"},{memberId:"11",name:"jack11"},{memberId:"10",name:"jack10"},{memberId:"7",name:"jack7"},{memberId:"4",name:"jack4"},{memberId:"3",name:"jack3"},{memberId:"2",name:"jack2"},{memberId:"1",name:"jack1"}];
const [numbers, setNumbers] = useState([1]);
useEffect(() => {
setNumbers();
}, []);
Expected output:
if members?.admins.length = 1~5
it shuld be
number = [1]
if members?.admins.length = 6~10
it shuld be
number = [1,2]
if members?.admins.length = 11~15
it shuld be
number = [1,2,3]
CodePudding user response:
let members = {admins: [1,2,3,4,5,6,7,8,9,10]}
console.log(Array(Math.ceil((members?.admins.length || 0) / 5)).fill(undefined).map((el, i) => i 1))
CodePudding user response:
let admins = ["a","b","c","d","e","f","g"];
let result = Array.from({length: Math.ceil(admins.length / 5)}, (_, i) => i 1);
console.log(result);
CodePudding user response:
You can use Math.ceil
to get the required length and then fill the array later.
const members = {
admins: Array(6)
}
const reqLength = Math.ceil(members?.admins?.length / 5);
const reqArray = Array(reqLength).fill().map((v, i) => i 1);
console.log(reqArray);
CodePudding user response:
Here you can create array using length
useEffect(() => {
const array = [...Array(Math.ceil( members?.admins.length / 5))].map((_, i)=> i 1)
setNumbers(array);
}, []);
CodePudding user response:
const members?.admins = [{memberId:"21",name:"jack21"},{memberId:"20",name:"jack20"},{memberId:"14",name:"jack14"},{memberId:"13",name:"jack13"},{memberId:"11",name:"jack11"},{memberId:"10",name:"jack10"},{memberId:"7",name:"jack7"},{memberId:"4",name:"jack4"},{memberId:"3",name:"jack3"},{memberId:"2",name:"jack2"},{memberId:"1",name:"jack1"}];
const [numbers, setNumbers] = useState([1]);
useEffect(() => {
let number = [];
let mb_length = members?.admins.length;
if(mb_length%5 === 0){
let mbb = (mb_length - mb_length%5)/5;
number = Array.from({length: mbb}, (_, i) => i 1)
}else{
let mbb = (mb_length - mb_length%5)/5;
number = Array.from({length: mbb 1}, (_, i) => i 1)
}
setNumbers(number);
}, []);