Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE alternative to Array.prototype.find() [duplicate]

Tags:

javascript

I previously wrote some code which matches uploaded files to their relevant clientID's, and displays them in a table to show which files are being assigned to which clients. The trouble is I tested this on Chrome and Safari as per the job spec and it works fine.

The problem is that this doesn't work on IE due to it not supporting Array.prototype.find() and they have now asked for it to be compatible with IE.

I have looked at other questions, but the answers were specific to their situation, often giving examples of other ways to do what they are looking for.

What would be the best way to achieve what I am trying to do?

var item = clientList.find(function(item) {

    return item.UniqueID == ClientID;

});
like image 661
user2924019 Avatar asked Apr 05 '17 19:04

user2924019


People also ask

What can I use instead of find in Javascript?

If you need a list of all matches, then you should use . filter() instead of . find() .

Can I use array prototype at ()?

Array.prototype.at() The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

What does find() return?

Definition and Usage The find() method returns the value of the first element that passes a test. The find() method executes a function for each array element. The find() method returns undefined if no elements are found. The find() method does not execute the function for empty elements.

What is flat()?

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.


1 Answers

You can create your own find function, the important part is to break loop when you match element.

var data = [{id: 1, name: 'a'}, {id: 2, name: 'b'}];

function altFind(arr, callback) {
  for (var i = 0; i < arr.length; i++) {
    var match = callback(arr[i]);
    if (match) {
      return arr[i];
    }
  }
}

var result = altFind(data, function(e) {
  return e.id == 2;
})

console.log(result)
like image 102
Nenad Vracar Avatar answered Oct 02 '22 02:10

Nenad Vracar