I have an array like this:
[{prop1:"abc",prop2:"qwe"},{prop1:"abc",prop2:"yutu"},{prop1:"xyz",prop2:"qwrq"}]
I'd like to get the index of all elements that satisfy a condition; in this case, when prop1 == "abc"
. So the desired output is something like [0,1]
.
Struggling to find a clean way of doing this?
indexes = a.findIndex(x => x.prop1==="abc")
will return 0
for the above array, because it stops at the first successful find.
I feel like I want something like this: indexes = a.filtered(x.index() => x.prop1==="abc")
The indexOf() method returns the first index (position) of a specified value. The indexOf() method returns -1 if the value is not found. The indexOf() method starts at a specified index and searches from left to right. By default the search starts at the first element and ends at the last.
TypeScript - Array indexOf() indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
The findIndex() method executes the callbackFn function once for every index in the array, in ascending order, until it finds the one where callbackFn returns a truthy value. If such an element is found, findIndex() immediately returns the element's index.
You can access an array element using an expression which contains the name of the array followed by the index of the required element in square brackets. To print it simply pass this method to the println() method.
You can use Array#reduce
method.
var data = [{prop1:"abc",prop2:"qwe"},{prop1:"abc",prop2:"yutu"},{prop1:"xyz",prop2:"qwrq"}];
console.log(
data.reduce(function(arr, e, i) {
if (e.prop1 == 'abc') arr.push(i);
return arr;
}, [])
)
// with ES6 arrow syntax
console.log(
data.reduce((arr, e, i) => ((e.prop1 == 'abc') && arr.push(i), arr), [])
)
With simple for
loop
var data = [{prop1:"abc",prop2:"qwe"},{prop1:"abc",prop2:"yutu"},{prop1:"xyz",prop2:"qwrq"}];
var res = [];
for (var i = 0; i < data.length; i++) {
if (data[i].prop1 == 'abc') res.push(i);
}
console.log(res)
Or use Array#filter
with Array#map
method(Not an efficient way since it needs to iterate twice).
var data = [{prop1:"abc",prop2:"qwe"},{prop1:"abc",prop2:"yutu"},{prop1:"xyz",prop2:"qwrq"}];
console.log(
data.map(function(e, i) {
return i;
}).filter(function(e) {
return data[e].prop1 == 'abc';
})
)
// With ES6 arrow syntax
console.log(
data.map((_, i) => i).filter(e => data[e].prop1 == 'abc')
)
You can use array.prototype.reduce
with shorthand if
to make it with a single line of code:
var arr = [ {prop1:"abc",prop2:"qwe"}, {prop1:"abc",prop2:"yutu"},{prop1:"xyz",prop2:"qwrq"} ];
var indexes = arr.reduce((m, e, i) => (e.prop1 === 'abc' && m.push(i), m), []);
console.log(indexes);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With