TerNovi TerNovi - 8 months ago 104
AngularJS Question

Passing argument to array.prototype.findIndex(callback[, thisArg])

I am having trouble passing an argument to the javascript array.prototype.findIndex(callback[, thisArg]) API. The javascript documentation specifies that an argument can be passed but I have not had luck.
This is the API reference Array.prototype.findIndex()

I see this syntax in API:

arr.findIndex(callback[, thisArg])

This is my current implementation but I don't like the way it is implemented with a globally created variable it is not easibly tested code.

var vm = this; //angular context
//List of objects
vm.someList = [{storeId: "1", name:"Carmel", quantity:"25", orderNumber:"12345"},
{storeId: "2", name:"Chocolate", quantity:"25", orderNumber:"23456"},
{storeId: "3", name:"Vanilla", quantity:"25", orderNumber:"34567"},
{storeId: "4", name:"Cinnamon", quantity:"25", orderNumber:"45678"}];

//List of items marked with priority
vm.priorityList = [{storeId: "3", name:"Vanilla", quantity:"25", orderNumber:"34567", priority: "true"}];

//For loop finds index of criteria to perform operation on someList[i] element
for(var i =0; i < vm.priorityList.length; i++){
//itemToFind created in global scope.
vm.itemToFind = vm.priorityList[i];
var index = vm.someList.findIndex(findPriorityIndex);
//Don't worry about the operation being performed.

//callback fn used
function findPriorityIndex(element, index, array){
return (element.storeId === vm.itemToFind.storeId
&& element.orderNumber ===vm.itemToFind.orderNumber);

I have tried to pass the argument to be used as thisArg in the callback with the following syntax but all resulted in failed attempts. Also I do acknowledge the API mentions the argument will be referenced as this inside the callback, and I have made such adjustment in the callback function.

vm.someList.findIndex(findPriorityIndex[, vm.priorityList[i]]);
vm.someList.findIndex([findPriorityIndex, vm.priorityList[i]]);

If anyone can provide any information as to how the argument should be passed to the callback function I will greatly appreciate it.


Basically you set with thisArg of findIndex, this in the callback.

for (var i = 0; i < vm.priorityList.length; i++) {
    index = vm.someList.findIndex(findPriorityIndex, vm.priorityList[i]);ยด
    //                                   set thisArg ^^^^^^^^^^^^^^^^^^

// callback fn used
function findPriorityIndex(element, index, array) {
    return element.storeId === this.storeId && element.orderNumber === this.orderNumber;
    //        access this here ^^^^                                and ^^^^