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
将str中的每个值映射到a中的索引。
str.map((str) => a.findIndex((ele) => str === ele.i))
You can use reduce()
method and includes()
to check if element exists in another array.
const a = [{"x":1,"y":1,"i":"Piechart1"},{"x":2,"y":1,"i":"Piechart2"},{"x":3,"y":1,"i":"Piechart3"}] const str = ["Piechart1", "Piechart3"]; const result = a.reduce((r, {i}, ind) => { return str.includes(i) && r.push(ind), r }, []) console.log(result)
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 => oi == 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.
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.