开发者

How should I implement a function to find indices of non-true elements of an array?

I have a function named uncompletedSteps():

function uncompletedSteps(completedSteps) {
    // completedSteps is an array
}

This function should examine completedSteps and return the index of all completedSteps elements that are not equal to true:

if (completedSteps[i] === true) {
    // add to return list
}

In other words, if have:

var completedSteps = [
   开发者_运维知识库 true,
    null,
    true
];

Then uncompletedSteps() should return [0, 2].

What should this uncompletedSteps() look like? (ECMAScript5 okay.)


Using reduce:

function uncompletedSteps(steps){
   return steps.reduce(function(memo, entry, i) { 
      return memo.concat(entry ? i : []);
   }, [])
}

Using forEach:

function uncompletedSteps(steps){
   var uncompleted = [];
   steps.forEach(function(entry,i) { 
      if(entry) uncompleted.push(i); 
   })
   return uncompleted;
}

Using map and filter

function uncompletedSteps(steps){
   return steps.map(function(entry, i) {
      return entry ? i : null;
   }).filter(function(entry) {
      return entry != null;
   });
}


var count = [];
for ( var i = 0; i<completedSteps.length; i++ ) {
  if(completedSteps[i]) {
    count.push(i);
  }
}
return count;


var arr = [true, true, null, true];
arr.map(function(el, i) { 
    return el ? i : -1; 
}).filter(function(el) {
    return el != -1;
})

Returns:

 [0, 1, 3]


This function should examine completedSteps and return the index of all completedSteps elements that are not equal to true:

Use the following process for backwards compatibility:

  • multiple replaces to insert the string null for values converted to empty strings
  • one replace to remove true
  • another replace with a replacer callback to insert indices
  • another replace to remove a leading comma
  • another replace to remove paired commas

For example:

function foo(match, offset, fullstring)
  {
  foo.i = foo.i + 1 || 0;
  if (match === "true") 
    {
    return "";
    }
  else
    {
    return foo.i;
    }
  }

function uncompletedSteps(node)
  {
  return String(node).replace(/^,/ , "null,").replace(/,$/ , ",null").replace(/,,/g , ",null,").replace(/[^,]+/g, foo).replace(/^,/,"").replace(/,,/g,",")
  }

var completedSteps = [
    null,
    true,
    false,
    true,
    null,
    false,
    true,
    null
];

uncompletedSteps(completedSteps); // "0,2,4,5,7"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜