获取数组中类型的第n项的索引

时间:2017-11-29 16:47:48

标签: javascript ecmascript-6

我有一个看起来像这样的数组:

let items = [
  1, '-', 231, '-', 6, 67, '-', 13, 177, 451, '-', 43, '-', 345, 56, 45
]

我想获得第n个-并返回其后的所有内容。所以我尝试了这个,起初我认为它正在工作,但是当我看到它时,我看到它正在获取索引然后从数组中的索引而不是破折号的索引。

因此,例如,如果n等于4,则当前正在获得第4个索引,而不是第4个索引处的第4个破折号。

let items = [
  1, '-', 231, '-', 6, 67, '-', 13, 177, 451, '-', 43, '-', 345, 56, 45
]

// Get the number of dashes
let stops = items.filter(i => i == '-').length
// Select a random dash
let n = Math.floor(Math.random() * stops)
// find the dash at the random position, then get a list of items that are not a dash
let sel = items.slice(n + 1).filter(r => r != '-')
// Select the first 3 items for the final output
let final = sel.slice(0, 3)

console.log(n)
console.log(final)

3 个答案:

答案 0 :(得分:3)

如果计数器达到零,您可以使用所需数字Array#findIndex进行递减,然后返回true



const
    items = [1, '-', 231, '-', 6, 67, '-', 13, 177, 451, '-', 43, '-', 345, 56, 45],
    getNth = n => items.slice(items.findIndex(v => v === '-' && !--n) + 1);

console.log(getNth(1));
console.log(getNth(2));
console.log(getNth(3));
console.log(getNth(4));
console.log(getNth(5));

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:2)

试试这个解决方案。代码中的注释描述。

let items = [
  1, '-', 231, '-', 6, 67, '-', 13, 177, 451, '-', 43, '-', 345, 56, 45
]


let stops = [];

// Push dashes indexes according to the `items` into the `stops`.
items.forEach((item, index) => item === '-' ? stops.push(index) : false); // false is done only for one line body
console.log(stops);

// Select a random dash
let n = Math.floor(Math.random() * stops.length);
console.log(n);

// find the dash at the random position and use that position to get from the `stops` array and use that value according to the `items`, then get a list of items that are not a dash
let sel = items.slice(stops[n] + 1).filter(r => r !== '-');

// Select the first 3 items for the final output
let final = sel.slice(0, 3);

console.log(final);

答案 2 :(得分:0)



let items = [
  1, '-', 231, '-', 6, 67, '-', 13, 177, 451, '-', 43, '-', 345, 56, 45
]
function getNth(value){
  var count = 0;
  var myIndex;
  items.forEach((item, index) => {
   if(item === "-"){
    count++;
    if(count === value ){
      myIndex = index;
    }
  }
  })

  return items.slice(myIndex);
}

console.log(getNth(2))
console.log(getNth(3))