a=[
{x:1,y:1,i:"Piechart1"},
{x:2,y:1,i:"Piechart2"},
{x:3,y:1,i:"Piechart3"}
]
str=["Piechart1","Piechart3"];
I want get index by comparing array string.Output in above example should be [0,2] Could you please let me know how to achieve in lodash ,javascript
Use .map()
to map the strings to their index, and .findIndex
inside the .map()
callback to locate the index of the object.
var a = [{x:1,y:1,i:"Piechart1"},{x:2,y:1,i:"Piechart2"},{x:3,y:1,i:"Piechart3"}];
var str = ["Piechart1","Piechart3"];
var res = str.map(s => a.findIndex(o => o.i == s));
console.log(res);
You can chain .filter(idx => idx != -1)
on the end if there's any chance of one of the strings not being in the main array.