Home > Mobile >  Loop over an array and return an array of each element in the array
Loop over an array and return an array of each element in the array

Time:08-12

I have an array that I am mapping over to create a list. When a user clicks one element I need to create an array with the index of all elements in that array. Then if an item at one of those indexes is clicked it is removed from the array. I am having trouble figuring out a method for creating the array of all indexes. My component is being sent each index one by one from a map so Ive tried pushing each index into an array but I end up with an array with only 1 index:

items = [{type
items.map((item, idx) => {
let indexes = [{type: "clickable", time: "11:41pm"}{type: "standard", time: "11:42pm"},{type: "clickable", time: "11:43pm"}, {type: "clickable", time: "11:45pm"}]

if(item.type == "clicklable"){
  indexs.push(idx)
}
console.log(indexes)
// [0]
// [2]
// [3]
}

How can I add all the indexes to one array?

CodePudding user response:

You can use .flatMap to map index and filter array at the same time.

const indexes = [{type: "clickable", time: "11:41pm"},{type: "standard", time: "11:42pm"},{type: "clickable", time: "11:43pm"},{type: "clickable", time: "11:45pm"}];

const clickableIndexes = indexes.flatMap(({ type }, idx) => type === 'clickable' ? idx : []);

console.log(clickableIndexes);
.as-console-wrapper { max-height: 100% !important; top: 0 }

CodePudding user response:

Please try this:

let indexes = [{type: "clickable", time: "11:41pm"},{type: "standard", time: "11:42pm"},{type: "clickable", time: "11:43pm"}, {type: "clickable", time: "11:45pm"}]
let indexs=[]
indexes.map((item)=>{
    indexs.push(item.type)
})
console.log(indexs)

CodePudding user response:

let indexes = [{type: "clickable", time: "11:41pm"},{type: "standard", time: "11:42pm"},{type: "clickable", time: "11:43pm"}, {type: "clickable", time: "11:45pm"}]

let indexs= indexes.map((item)=>item.type)
console.log(indexs)

CodePudding user response:

You can try mapping each item to either their index number or false with short circuiting and then filtering by Number.isInteger

const items = [
    { type: 'clickable', time: '11:41pm' },
    { type: 'standard', time: '11:42pm' },
    { type: 'clickable', time: '11:43pm' },
    { type: 'clickable', time: '11:45pm' },
];

const indices = items.map((item, idx) => item.type === 'clickable' && idx)
    .filter(Number.isInteger);
    
console.log(indices);

  • Related