This is my array:
[{
name: "Test",
skills: {
agile: true,
good: true
}
},
{
name: "Test 2",
skills: {
agile: false,
good: false
}
}]
I need to find the last element (his index) who has the skill good set to true. The only way I know to fix this is to use a for/if combination. Is there any other faster/optimal way to do it ?
Use filter:
const goodSkills = myArray.filter(x => x.skills.good)
Then get the last item:
goodSkills[goodSkills.length - 1]
Or if you only need the index, and we treat name
as a unique key:
const lastGoodIndex = myArray.findIndex(x => x.name === goodSkills[goodSkills.length - 1].name)
You can then use lastGoodIndex
for whatever nefarious purpose you have in mind.
Alternatively if name
is not a unique key, I suggest just using forEach
:
let lastGoodIndex;
myArray.forEach((x, i) => lastGoodIndex = x.skills.good ? i : lastGoodIndex);
console.log(lastGoodIndex);
The fastest way is to us a for loop:
var arr = [{ name: "Test", skills: { agile: true, good: true } }, { name: "Test 2", skills: { agile: false, good: false }, }] function findLastGoodIndex(arr) { for (let i = arr.length - 1; i >= 0; i--) { if (arr[i].skills.good) { return i; } } } console.log(findLastGoodIndex(arr));
Or if the list isn't that large you can combine reverse
with findIndex
:
arr.reverse().findIndex(x => x.skills.good));
You can do it in 3 rows:
var arr = [ { name: "Test", skills: { agile: true, good: true } }, { name: "Test 2", skills: { agile: false, good: false }, } ] var lastIndex; arr.forEach(function(item, i) { if(item.skills.good) lastIndex = i; }) console.log(lastIndex);
If you want the index
of last element that has good = true
your best option is to use for/if
(perhaps going backwards, ie i--
if you can guess where can you expect the good
item?).
filter
will find the item(s) too, and it also has index
property, but generally it's slower than for/if.
forEach
will also generally be slower than for/if
.
edit:styling.
Since you need to search the last value, you should search in descending order. This would prevent any unnecessary iterations.
var data = [{ name: "Test", skills: { agile: true, good: true } }, { name: "Test 2", skills: { agile: false, good: false } } ]; var i = data.length; var result = null; while (i--) { if (data[i].skills.good) { result = i; break; } } console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.