从双“ for”循环中获取所有出现的值的索引

时间:2019-02-19 16:45:42

标签: javascript arrays for-loop

首先,如果标题不够精确,可以随意编辑。

JS绝对不是我的领土。 我正在尝试编写此自定义JS回调,除了索引获取线外,它确实满足我的要求。 但是,因为我已经在双for循环内,所以我不知道如何推动正确

(正确的意思是:在推送到“ partial_data”变量之前,“活动所有者”变量中存在的每个值出现所处的索引)

索引到索引var。现在看来,它只会返回首次出现的索引。

var full_data = ['a', 'b', 'c', 'd', 'a', 'g', 'g', 'h']
var partial_data = []
var active_holder = ['a', 'g']
var indexes = []

for (j = 0; j < full_data.length; j++) {

    for (z = 0; z < active_holder.length; z++) {

        if (active_holder[z].includes(full_data[j])) {

            indexes.push(full_data.indexOf(full_data[j]));
            partial_data.push(full_data[j]);
        }
    }
}

console.log(partial_data) // * ['a', 'a', 'g', 'g'] // 
console.log(indexes) // * [0, 0, 5, 5] // WRONG, should be 0,4,5,6 or something along

有什么建议吗?

3 个答案:

答案 0 :(得分:2)

您可以使用reduceincludes

const fullData = ['a', 'b', 'c', 'd', 'a', 'g', 'g', 'h']
const active = ['a', 'g']

let {partial, index} = fullData.reduce((op,inp,index)=>{
  if( active.includes(inp) ){
    op.partial.push(inp)
    op.index.push(index)
  }
  return op
},{partial:[],index:[]})

console.log(partial)
console.log(index)

答案 1 :(得分:1)

您可以使用reduce方法并返回一个包含索引和部分数据的对象。

var data = ['a', 'b', 'c', 'd', 'a', 'g', 'g', 'h']
var active = ['a', 'g']

const {
  index,
  partial
} = data.reduce((r, e, i) => {
  if (active.includes(e)) {
    r.index.push(i)
    r.partial.push(e)
  }
  return r
}, {
  index: [],
  partial: []
})


console.log(index)
console.log(partial)

答案 2 :(得分:0)

您在indexOf时再次呼叫push()。您应该只push() j

  

indexOf :返回数组中值的首次出现的索引

var full_data = ['a', 'b', 'c', 'd', 'a', 'g', 'g', 'h']
var partial_data = []
var active_holder = ['a', 'g']
var indexes = []

for (j = 0; j < full_data.length; j++) {

    for (z = 0; z < active_holder.length; z++) {

        if (active_holder[z].includes(full_data[j])) {

            indexes.push(j);
            partial_data.push(full_data[j]);
        }
    }
}

console.log(partial_data) // * ['a', 'a', 'g', 'g'] // 
console.log(indexes) // * [0, 0, 5, 5] // WRONG, should be 0,4,5,6 or something along