te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>indexOf() when array-elements are objects (javascript) - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

indexOf() when array-elements are objects (javascript) - Stack Overflow

programmeradmin2浏览0评论

For instance, a variable named arrayElements of type array contains:
[{id:1, value:5},{id:2, value:6},{id:3, value:7},{id:4, value:8}].

How do I get the position of the array element with id === 3(3rd element) in the arrayElements variable besides using loop?

thanks.

For instance, a variable named arrayElements of type array contains:
[{id:1, value:5},{id:2, value:6},{id:3, value:7},{id:4, value:8}].

How do I get the position of the array element with id === 3(3rd element) in the arrayElements variable besides using loop?

thanks.

Share Improve this question edited Nov 4, 2014 at 16:05 jcera 3452 silver badges11 bronze badges asked Nov 4, 2014 at 15:21 Julian BergerJulian Berger 1771 silver badge10 bronze badges 0
Add a ment  | 

6 Answers 6

Reset to default 7
const arrayElements = [
  { id: 1, value: 5 },
  { id: 2, value: 6 },
  { id: 3, value: 7 },
  { id: 4, value: 8 }
]

console.log(arrayElements.findIndex((item) => item.id === 3))

You have to loop at one point. But you can abstract it to look like you're not looping

function indexOfCallback(arr, callback, startIndex) {
    if (typeof startIndex == 'undefined') {
        startIndex = 0;
    }
    for(var i=startIndex; i < arr.length; i ++) {
        if (callback(arr[i])) {
            return i;
        }
    }
    return -1;
}

var array = [{id:1, value:5},{id:2, value:6},{id:3, value:7},{id:4, value:8}];
// Search on id === 3
console.log(indexOfCallback(array, function(obj){
    return obj.id === 3;
}));
// Search on value === 6
console.log(indexOfCallback(array, function(obj){
    return obj.value === 6;
}));

As mentioned by Anthony, this is proposed for ECMAScript 6. Here's the more plete polyfill https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

if (!Array.prototype.findIndex) {
  Array.prototype.findIndex = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return i;
      }
    }
    return -1;
  };
}
console.log(array.findIndex(function(obj){
    return obj.id === 3;
}));
arrayElements.map(o => o.id).indexOf(3);

Notes:

  • Possibly slower than a loop because transforms whole array prior to search. But with high-level languages like Javascript, you never know.
  • Infinitely more readable than a loop.
  • IE patible (unlike findIndex as of 2017).

In an array like this, you cant access elements by id. So using a loop is the best solution you have. However, depending on your use case you could also consider using an object instead of an array for direct access.

var container = { 1: {id:1, value:5}, 2: {id:2, value:6}, 3: {id:3, value:7} }

You can use an array filter but I think that you will get a better solution using a loop.

var array = [{id:1, value:5},{id:2, value:6},{id:3, value:7},{id:4, value:8}];

var result = array.filter(condition);

function condition(value, index){
    if (value.id === 3) return index;
}

console.log(result);

I wrote a function for you that you can use get the job done, but it uses a loop:

var yourObjArray = [{id:1, value:5},{id:2, value:6},{id:3, value:7},{id:4, value:8}];


function objArrayIndex(objArray){
  for(var i = 0; i < objArray.length; i++){
    if(objArray[i]['id'] == 3){
      return i;
    }
  }
  return -1;
}

console.log(objArrayIndex(yourObjArray));
发布评论

评论列表(0)

  1. 暂无评论