如何保持检查数组直到满足特定条件

时间:2019-08-28 12:29:52

标签: javascript arrays typescript optimization

我有两个数组idarrayarray,并且想在item_tosearch中找到idarray。然后使用找到的索引循环遍历idarray直到找到不是-1的元素。然后使用该索引从array中检索值。

据我所知,在这种情况下,如果要继续检查,可以使用forwhileforeach进行任何形式的迭代,我有2个数组。第一个用于idarray,第二个用于array。我设法检查了下一个数据是什么,以及数据是否已达到最终值。只要id不是-1,我还可以获得我想要的下一个数据。

我尝试过的事情:

var item_tosearch = 0;
var idarray = [-1, 2, -1, 4, -1]
var array = [3, 2, 1, 0, 7];
var index = array.indexOf(item_tosearch);

if (index > -1) {
  var res = array.slice(index);
}

if (res != undefined) {
  for (let i = 0; i < res.length; i++) {
    if (res[i + 1] != undefined) {
      if (idarray[index + 1] == -1) {
        if (res[i + 2] != undefined) {
          console.log("Next = " + res[i + 2]);
          break;
        } else {
          console.log("Final index");
          break;
        }
      } else {
        console.log("Next = " + res[i + 1]);
        break;
      }
    } else {
      console.log("Final index");
    }
  }
} else {
  console.log('data not found');
}

我的问题是,有什么方法可以改进该方法?

任何建议都很珍贵。


说明:

如果我具有以下条件:

idarray = [-1,2,-1,4,1]; 数组= [3,2,1,0,7];

我想拥有的是,如果我在item_tosearch上输入2作为值,我期望具有:0作为返回值,因为它是id中没有-1的下一项。


另一种情况,如果我有:

idarray = [-1,2,-1,-1,1]; 数组= [3,2,1,0,7];

如果我在item_tosearch上输入2作为值,则期望具有:7作为返回值,因为它是ID中没有-1的下一项。

但是,如果idarray为= [-1,2,-1,-1,-1],且item_tosearch上的2为值。我希望将返回“最终索引”。因为没有更多的项目没有-1作为ID。

我尝试了另一次迭代来获取,但似乎没有得到我想要的东西:

var item_tosearch = 2;
var idarray = [-1, 2, -1, -1, -1]
var array = [3, 2, 1, 0, 7];
var index = array.indexOf(item_tosearch);

if (index > -1) {
  var res = array.slice(index);
}

if (res != undefined) {
  for (let i = 0; i < res.length; i++) {
    if (res[i + 1] != undefined) {
      if (idarray[index + 1] == -1) {
        for (let j = i + 1; j < res.length - i; j++) {
          if (res[j + 1] != undefined) { // fetch if still got data with id != -1
            console.log("Next = " + res[j + 1]); // should show next item without -1 in id
            break;
          } else {
            console.log("Final index"); // reach end of array
            break;
          }
        }
      } else {
        console.log("Next = " + res[i + 1]); // should show next item without -1 in id
        break;
      }
    } else {
      console.log("Final index"); // reach end of array
    }
  }
} else {
  console.log('data not found');
}

2 个答案:

答案 0 :(得分:1)

好的,我认为我有点理解逻辑,但是我不确定。 是问题:I want to check if any of the ids following the id corresponding with my value, is not -1吗?

希望我能正确理解逻辑。

如果您没有使用可重用的功能,或者不关心结构,也可以写得很短:

var pos = 0;
var idarray = [ -1, 2, -1, 4, -1 ];
var array = [ 3, 2, 1, 0, 7 ];

var get_result = ( array, idarray, pos, ex ) => {
  const offset = array.indexOf( pos ) + 1;
  return idarray
    .slice( offset )
    .reduce(( result, id, index ) => {
      if ( result === "final index" && id !== -1 ) result = array[ index + offset ];
      return result;
    }, "final index" );
};

// example 1:
const ex1_search_value = 0; // pos
const ex1_ids = [ -1, 2, -1, 4, -1 ]; // idarray
const ex1_values = [3, 2, 1, 0, 7]; // array
// expect "final index", since our range will only contain the last id, which is -1
const result1 = get_result( ex1_values, ex1_ids, ex1_search_value );
console.log( `expect final index, ${ result1 }` );

// example2:
const ex2_search_value = 2;
const ex2_ids = [ -1, 2, -1, -1, -1 ];
const ex2_values = [3, 2, 1, 0, 7];
// expect "final index", since our range is the last two items, both with id -1
const result2 = get_result( ex2_values, ex2_ids, ex2_search_value );
console.log( `expect final index, ${ result2 }` );

// example3:
const ex3_search_value = 2;
const ex3_ids =    [ -1, 2, -1, -1, -1, -1, -1, -1, -1, 3, -1,  2, -1, -1 ];
const ex3_values = [  3, 2,  1,  0,  7,  4,  9, 14, 74, 8, 45, 14, 17, 84 ];
// expect { id: 3, value: 8 }
const result3 = get_result( ex3_values, ex3_ids, ex3_search_value );
console.log( `expect 8, ${ result3 }` );

// example4:
const ex4_search_value = 2;
const ex4_ids =    [-1, 2, -1, 4, 1];
const ex4_values = [ 3, 2,  1, 0, 7];
// expect { id: 4, value: 0 }
const result4 = get_result( ex4_values, ex4_ids, ex4_search_value );
console.log( `expect 0, ${ result4 }` );

// example5:
const ex5_search_value = 2;
const ex5_ids =    [-1, 2, -1, -1, 1];
const ex5_values = [ 3, 2,  1,  0, 7];
// expect { id: 1, value: 7 }
const result5 = get_result( ex5_values, ex5_ids, ex5_search_value );
console.log( `expect 7, ${ result5 }` );

// example6:
const ex6_search_value = 2;
const ex6_ids =    [-1, 2, -1, -1, -1];
const ex6_values = [ 3, 2,  1,  0,  7];
// expect "final index"
const result6 = get_result( ex6_values, ex6_ids, ex6_search_value );
console.log( `expect final index, ${ result6 }` );

我这里的另一种方法是将数组合并到一个包含对象的数组中,这样我们就不必检查未定义的值,而仍然能够使用数组方法而不是普通循环。如果您必须在此之后的代码中大量使用ID /值组合,这将有所帮助。这些功能可以使所有内容重用。

// Create an object from the id and value combinations.
const create_collection = ( ids, values ) => {
  return ids.map(( id, index ) => ({
    id,
    value: values[ index ]
  }));
};

const has_valid_descendants = ( collection, search_value ) => {
  // Find the index of the first item that has our requested value.
  const search_index = collection.findIndex( item => item.value === search_value );
  // Slice the relevant part from the collection.
  // Since we will only look at records past the item ahving the search_value, we mights well only slice the relevant parts.
  const collection_in_range = collection.slice( search_index + 1 );
  // Find the first item in range has an id that is not -1.
  return collection_in_range.find( item => item.id !== -1 ) || 'final index';
};


// example 1:
const ex1_search_value = 0; // pos
const ex1_ids = [ -1, 2, -1, 4, -1 ]; // idarray
const ex1_values = [3, 2, 1, 0, 7]; // array
// Collection should be: [{ id: -1, value: 3 },{ id: 2, value: 2 },{ id: -1, value: 1 },{ id: 4, value: 0 },{ id: -1, value: 7 }];
const ex1_collection = create_collection( ex1_ids, ex1_values );
console.log( ex1_collection );
// Is there a valid next item?
// expect "final index", since our range will only contain the last id, which is -1
const ex1_result = has_valid_descendants( ex1_collection, ex1_search_value );
console.log( 'expect 1: "final index"' );
console.log( `example 1: ${ JSON.stringify( ex1_result ) }` );


// example2:
const ex2_search_value = 2;
const ex2_ids = [ -1, 2, -1, -1, -1 ];
const ex2_values = [3, 2, 1, 0, 7];
// expect "final index", since our range is the last two items, both with id -1
const ex2_result = has_valid_descendants(
  create_collection( ex2_ids, ex2_values ),
  ex2_search_value
);
console.log( 'expect 2: "final index"' );
console.log( `example 2: ${ JSON.stringify( ex2_result ) }` );


// example3:
// We add a bunch of other values and ids.
// This proves it will work with longer arrays as well
// and that the result is the first item without the id -1
const ex3_search_value = 2;
const ex3_ids =    [ -1, 2, -1, -1, -1, -1, -1, -1, -1, 3, -1,  2, -1, -1 ];
const ex3_values = [  3, 2,  1,  0,  7,  4,  9, 14, 74, 8, 45, 14, 17, 84 ];
// expect { id: 3, value: 8 }
const ex3_result = has_valid_descendants(
  create_collection( ex3_ids, ex3_values ),
  ex3_search_value
);
console.log( 'expect 3: { id: 3, value: 8 }"' );
console.log( `example 3: ${ JSON.stringify( ex3_result ) }` );


// example4:
// Note: I've added || 'final index'; to the has_valid_descendants() function.
const ex4_search_value = 2;
const ex4_ids = [-1, 2, -1, 4, 1];
const ex4_values = [3, 2, 1, 0, 7];
// expect { id: 4, value: 0 }
const ex4_result = has_valid_descendants(
  create_collection( ex4_ids, ex4_values ),
  ex4_search_value
);
console.log( 'expect 4: { id: 4, value: 0 }' );
console.log( `example 4: ${ JSON.stringify( ex4_result ) }` );


// example5:
// Note: I've added || 'final index'; to the has_valid_descendants() function.
const ex5_search_value = 2;
const ex5_ids = [-1, 2, -1, -1, 1];
const ex5_values = [3, 2, 1, 0, 7];
// expect { id: 1, value: 7 }
const ex5_result = has_valid_descendants(
  create_collection( ex5_ids, ex5_values ),
  ex5_search_value
);
console.log( 'expect 5: { id: 1, value: 7 }' );
console.log( `example 5: ${ JSON.stringify( ex5_result ) }` );


// example6:
// Note: I've added || 'final index'; to the has_valid_descendants() function.
const ex6_search_value = 2;
const ex6_ids = [-1, 2, -1, -1, -1];
const ex6_values = [3, 2, 1, 0, 7];
// expect "final index"
const ex6_result = has_valid_descendants(
  create_collection( ex6_ids, ex6_values ),
  ex6_search_value
);
console.log( 'expect 6: "final index"' );
console.log( `example 6: ${ JSON.stringify( ex6_result ) }` );

答案 1 :(得分:1)

如果我对您的问题了解得足够多,那么您正在寻找类似的内容。即使这不是您想要的解决方案,您也可能会从中得到一些启发。

  • 此解决方案首先在idarray中找到要搜索的元素的索引。如果找不到,请返回undefined
  • 接下来,从更高的1个索引开始循环,直到idarray的结尾。如果发现不是-1的元素,则从array返回当前索引上的元素。
  • 如果未找到任何内容,则返回undefined

var idarray, array;

function giveThisABetterName(item_tosearch, idarray, array) {
  var index = idarray.indexOf(item_tosearch);
  if (index === -1) return; // data not found

  for (index += 1; index < idarray.length; ++index) {
    if (idarray[index] !== -1) return array[index];
  }
  
  // reach end of array
}

idarray = [-1, 2, -1, 4, 1];
array   = [ 3, 2,  1, 0, 7];
console.log(giveThisABetterName(2, idarray, array));

idarray = [-1, 2, -1, -1, 1];
array   = [ 3, 2,  1,  0, 7];
console.log(giveThisABetterName(2, idarray, array));

idarray = [-1, 2, -1, -1, 1];
array   = [ 3, 2,  1,  0, 7];
console.log(giveThisABetterName(9, idarray, array));