简体   繁体   中英

Find position of element in array of elements with jQuery

I have two arrays representing the states of a list before and after being sorted:

var $before = $('li');
// SORTING
var $after = $('li');

Now I want to pick a specific item var $item = $after.filter(':first-child') and find the position it had in the $before list. What I am doing so far works:

var beforeIndex = false;

$.each($before, function(i, v) {

  if($(v)[0] == $item[0]) {

    beforeIndex = i;

  }

})

However, I feel like there should be a simpler solution, something like:

$before.find(x => $(x)[0] == $item[0]);

(which doesn't work). Any ideas? :)

You can solve this as below. I tried to use a minimal example.

 var $li = $("ul > li"); var $item = $li.filter(':last-child'); var result = Array.prototype.findIndex.call($li, (li) => { return $item.is($(li)); }); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> 

Just use a data attribute, than there is no looking it up.

 // Loop over the lis and set a data attribute with the index $("li").each(function (index) { $(this).data("orginalIndex", index) }) // some random sort code to change the order $("ul").append($("li").sort(function(){ return Math.random() > .5 ? 1 : -1 })) // loop over the newly sorted lis and read the text and old index $("li").each(function () { var elem = $(this); console.log(elem.text(), elem.data("orginalIndex")) }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM