Reputation: 75
We know that find() method returns the value of the first array element that passes a test function.
But in the below case what if I need all the elements?
<p id="myPEle">
</p>
const listIds = ["Vanilla","Vanilla"];
const itemId = 'Vanilla';
for(let i=0; i< listIds.length; i++){
const result = listIds.findIndex(id => id === itemId)
document.getElementById("myPEle").innerHTML += result;
}
Well I need the result to be '01' instead of '00'
Upvotes: 0
Views: 101
Reputation: 3809
Well I need the result to be '01' instead of '00'
If you really need to get indexes and not values - use map
function.
const listIds = ["Vanilla","Vanilla"];
const itemId = 'Vanilla';
const result = listIds.map((id, index) => id === itemId && index)
.filter(x => x !== false); // Thanks @vlaz
console.log(result); // [0,1]
Otherwise - use filter
method
const listIds = ["Vanilla","Vanilla"];
const itemId = 'Vanilla';
const result = listIds.filter(id => id === itemId);
console.log(result); // ["Vanilla","Vanilla"]
Upvotes: 0
Reputation: 1345
const listIds = ["Vanilla", "Vanilla"];
const itemId = 'Vanilla';
const result = listIds.filter(id => id === itemId) //use filter method
.map((item,index)=>index) //get array of index of filtered items
.join(""); //join array item
document.getElementById("myPEle").innerHTML = result ;
<p id="myPEle"></p>
If listIds array is big in size the then I would suggest to use "array.reduce" instead of filter in order to avoid multiple iteration on array which will perform filtering and mapping in one iteration check for more on reduce
Upvotes: 3
Reputation: 5941
Here's an approach that uses reduce
and join
prototype methods. I added a couple of additional strings to listIds
to show that it works:
function generateIdxString(array, target) {
return listIds.reduce((a, el, idx) => {
if (el === itemId) {
a.push(idx);
}
return a;
}, []).join('');
}
const listIds = ["Vanilla", "Vanilla", "Chocolate", "Strawberry", "Vanilla"];
const itemId = "Vanilla";
document.querySelector('#myPEle').innerHTML = generateIdxString(listIds, itemId);
<p id="myPEle"></p>
Upvotes: 0
Reputation: 68933
In both the iteration of the loop, you are getting the same index (0
) because
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
You can use forEach()
to check the item in each iteration. If the current item is equal to the itemId
, you can store the index.
Please Note: To add text into an element it is better to use textContent
instead of innerHTML
.
const listIds = ["Vanilla","Vanilla"];
const itemId = 'Vanilla';
listIds.forEach(function(el,i){
if(itemId == el)
document.getElementById("myPEle").textContent += i;
});
<p id="myPEle">
</p>
Upvotes: 0