1

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?

asked Aug 12, 2022 at 5:04
0

3 Answers 3

2

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 }

answered Aug 12, 2022 at 5:24
Sign up to request clarification or add additional context in comments.

Comments

0

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)

answered Aug 12, 2022 at 5:16

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

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);

answered Aug 12, 2022 at 5:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.