ecrmnn / collect.js

💎  Convenient and dependency free wrapper for working with arrays and objects
https://collect.js.org
MIT License
6.54k stars 313 forks source link

Invalid `search` results #309

Closed edwinvdpol closed 2 months ago

edwinvdpol commented 2 years ago

Hi there,

I already saw a few issues which were related to search, but can someone explain this behaviour? I am searching for a string value.

const { collect } = require('collect.js'); 

const c = collect(['0', '00', '000', '0-0', '0*0', '0&0']);
// Collection { items: [ '0', '00', '000', '0-0', '0*0', '0&0' ] }

c.search('0', true); // Result: 0
c.search('00', true); // Result: 1 (correct!)
c.search('000', true); // Result: 2
c.search('0-0', true); // Result: 3
c.search('0&0', true); // Result: 5
c.search('0&0', true); // Result: 5

Am I doing to something wrong here?

Thanks, Edwin

jjjrmy commented 1 year ago

This is expected behavior, as per the documentation:

The search method searches the collection for the given value and returns its key if found. If the item is not found, false is returned.

I have also confirmed the same results using Laravel's Collection.

You are using all strings in your collection, so there is no reason to pass true as the second parameter.

This issue should be closed.