【问题标题】:How to keep checking array until certain condition is met如何在满足特定条件之前一直检查数组
【发布时间】:2019-08-28 12:29:52
【问题描述】:

我有两个数组idarrayarray,想在idarray 中找到item_tosearch。然后使用找到的索引循环向前遍历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');
}

【问题讨论】:

  • 您能用文字解释一下您要计算的内容吗?您似乎想知道某些值是否仍然存在,但是通过比较residarray 的长度应该很容易。因此,您能更好地解释逻辑吗?因为我们可能可以使用.forEach().filter().find() 等数组方法对其进行编码,从而使整体更具可读性。
  • @Shilly 实际上,array 和 idarray 是基于同一级别的。但是我从前端值获取 id 而数组来自后端,如果 id 不是-1,我会计算下一个项目。如果是,那么我将获取下一个项目。但是您可以注意到,如果 idarray 值更改为: [-1, 2, -1, -1, -1] 和 pos 到 2,您会发现它没有返回“最终索引”控制台,因为我需要递归增加+ 值在:if (res[i + 2] != undefined) { console.log("Next = " + res[i + 2]); 但我还没有设法这样做。我希望这已经足够清楚了。
  • @Shinjo 我不认为你明白这一点。您讲述了太多细节,而我们不知道您尝试使用当前代码实现什么。我们可以尝试对您的问题进行逆向工程,但大多数人没有时间或意愿这样做。让我给你一个简短的例子:我有两个数组,并试图找出这些数组是否共享任何元素。我目前有以下代码:...我当前的问题是...
  • @3limin4t0r 对不起,m_m 我已经添加了具有某些值时期望的示例。又一次尝试迭代它。
  • @Shinjo 这已经好多了。 ??????

标签: javascript arrays typescript optimization


【解决方案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));

【讨论】:

  • 如果两个数组的长度变化很大,您可能需要将index &lt; idarray.length 更改为index &lt; idarray.length &amp;&amp; index &lt; array.length,因为没有必要找到将返回undefined 的索引,因为它超过了长度array.
  • 感谢您的帮助。是的,在稍微优化你的功能后,我得到了我想要的东西:jsfiddle.net/91o0ztsw
【解决方案2】:

好的,我想我有点理解其中的逻辑,但我不确定。 问题是: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/value 组合,这将有所帮助。这些功能只是为了让一切都可重用。

// 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 ) }` );

【讨论】:

  • 对不起,如果我之前不够清楚,m_m 我已经添加了示例,并再次尝试迭代。 “我想检查与我的值对应的 id 后面的任何 id 是否不是 -1 ?”它不是。我想检查要搜索的数据中的下一项是否在值中有-1,如果确实有-1,则跳过直到找到!= = -1,或者如果下一项没有任何剩余,则返回“最终索引”带有 != -1 的 ID。
  • 我看不出有什么不同。您希望继续检查 ID,直到找到一个不是 -1 的 ID,或者如果没有,则为“最终索引”,因为您提到需要递归检查。我稍微更新了最短代码以返回值而不是 id 或“最终索引”,但算法是相同的。对于使用对象的较长代码,如果长度为 0,我只需要添加 || "final index" 以使其返回最终索引。您的两个额外示例都适用于我的代码,所以我认为我的代码都是正确的。
  • to make it return final index if the length is 0 应该是 to make it return final index if no object is found。而你的价值显然在result.value 之内。
  • 是的。我对这两个答案都投了赞成票。只是我不能同时接受两个答案。
猜你喜欢
  • 2016-05-30
  • 2011-07-10
  • 2020-08-29
  • 2019-11-11
  • 1970-01-01
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
相关资源
最近更新 更多