1

So, I am trying to figure out a situation where I would populate an array (b[]) with the index numbers from another array (a[]) whose elements meet a certain criteria (array b would be index numbers based on array a which is an array of images, and would populate b when width is greater than height).

So, I came up with a hypothetical function in hopes of getting an array output where I would get a listing from a[] that align with values from b[]. Needless to say, neither attempt came up with anything of value.

var a = ['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi'];
var b = [2, 4, 5];


var d = function(a, b) {
  var func1 = [];
  var func2 = [];

  for(i = 0; i > b.length; i++) {
    func1.push(a[b[i]]);
  }

  console.log('func1 = ' + func1); // 'func1 = []'

  for(i=0; i > a.length; i++) {
    if(b.indexOf(a.indexOf(a[i])) > -1) {
      func2.push(a[i])
    }
  }
  console.log('func2 = ' + func2); // 'func2 = []'
}


d(a,b) // Ideally outputs ['cd', 'ef', 'fg']

Is this a matter of function scope, or am I missing the point of .push?

2
  • 2
    use "<" instead of ">" in your for loops Commented Aug 4, 2016 at 17:11
  • 1
    That was awfully derpy of me. Thanks! Commented Aug 4, 2016 at 17:14

2 Answers 2

1

The comparisons in your for loops are backwards. They should be like this:

for(i = 0; i < b.length; i++) {
    func1.push(a[b[i]]);
  }

  console.log('func1 = ' + func1); // 'func1 = []'

  for(i=0; i < a.length; i++) {
    if(b.index(a.indexOf(a[i])) > 1) {
      func2.push(a[i])
    }
  }

Also, b.index is not a function. I assume you meant indexOf:

var a = ['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi'];
var b = [2, 4, 5];


var d = function(a, b) {
  var func1 = [];
  var func2 = [];

  for(i = 0; i < b.length; i++) {
    func1.push(a[b[i]]);
  }

  console.log('func1 = ' + func1); // 'func1 = []'

  for(i=0; i < a.length; i++) {
    if(b.indexOf(a.indexOf(a[i])) > 1) {
      func2.push(a[i])
    }
  }
  console.log('func2 = ' + func2); // 'func2 = []'
}


d(a,b) // Ideally outputs ['cd', 'ef', 'fg']

This outputs:

func1 = cd,ef,fg
func2 = fg
Sign up to request clarification or add additional context in comments.

1 Comment

It was meant to be if(b.indexOf(a.indexOf(a[i])) > -1). In terms of efficiency, is func1 better than func2 since it has less loops to go through?
0

use for(i=0; i < a.length; i++) instead! Proper syntax is the key to success! Thanks @Superdrac

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.