ms_nitrogen ms_nitrogen - 4 months ago 7
Javascript Question

How to get values from one array based on another array?

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
?

Answer

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
Comments