创建键数组和值数组数组

时间:2017-09-21 00:41:26

标签: javascript arrays dataset nested-loops

我有一个同义词库应用程序,因此用户可以输入" dog"作为一个基础词," canine,hound,mutt"作为同义词。 然后将它们添加到数据库中。 随着添加" dog"作为基本单词,我想为每个同义词制作多个同时条目,这样用户就不必返回并输入" hound"其次是" dog,canine,mutt"。这将涉及多份表单提交。

基于上面的例子,我想在前往数据库之前创建以下数据集:

var Keys = 
[
    dog,canine,mutt,hound
];

var Values = [
    [mutt,canine,hound],[dog,mutt,hound],[canine,dog,hound],[dog,canine,mutt]
];

有了这个,我可以通过每个键做一个简单的循环,并在Values中获取相应的数组,并执行我的插入。例如,当根据它们的长度进行迭代时,我会抓住索引2并得到一个' mutt'然后抓住' [犬,狗,猎犬]的价值。 到目前为止,我尝试执行所需的嵌套循环以实现此数据集并未获得丰硕成果。

到目前为止,我已经尝试了这一点,并希望得到一些建议:

    var baseWord = [];
    baseWord.push("dog");
    var synonyms = ["hound","mutt","canine"];
    var words = baseWord.concat(synonyms);                  
    console.log(words.length); //outputs 4

    //new arrays to hold the result of the inner loop calculation
    var Keys = [];
    var Values = [];
    for(var i = 0; i < words.length; i++){
        //removing the inner loops makes this output, the 4 values from the 'words' variable. with the inclusion of the loops, we only get back 'dog'
        keys.push(words[i]);


        for(var x = 0; x < words.length; x++){
            //I want to loop through the 'words' variable, and if current index of 'words' matches a value in tempValues(matches a different value of tempValues each time, which is what i'd want(it allows us to ignore the current key, and keep the values), then remove that particular value from tempValues, then push the remaining values in tempValues into our 'VAlues' array that we declared ouside all of these loops
            var tempValues = words;
            //console.log("tempvalues is :: %s", JSON.stringify(tempValues));
                for(var o = 0; o < words.length; o++){
                    if(words[o] === words[x]){
                        //get rid of the value in tempValues that is equals to the value of the key in the outer loop(for this particular iteration)
                        tempValues.splice(tempValues[o]);
                    }
                    console.log(JSON.stringify(tempValues));
                }
                Values.push(tempValues);
        };
    };
    console.log("the new keys array is :: %s", JSON.stringify(Keys)); //keep getting dog
    console.log("the new values array is :: %s", JSON.stringify(Values)); //keep getting [[]]

3 个答案:

答案 0 :(得分:2)

尝试这样的事情:

&#13;
&#13;
//OP code
var baseWord = [];
baseWord.push("dog");
var synonyms = ["hound", "mutt", "canine"];
var words = baseWord.concat(synonyms);
console.log(words.length); //outputs 4

//and new code
//put result into an object
var dictionary = {};
for (var i = 0, w; w = words[i]; ++i) {
  //take each word (w)
  dictionary[w] = words.filter(function(word) {
    return word != w; //all words except w
  });
}
//take the object
console.log(dictionary);
//or stringify it
console.log(JSON.stringify(dictionary));

//Just for OP
console.log('direct answer');
var keys = words.map(function(word) {
  return word;
});
console.log('Keys :: ' + JSON.stringify(keys));//same as "words"

var values = words.map(function(word) {
  return words.filter(function(w) {
    return word != w; //all words except w
  });
});
console.log('Values :: ' + JSON.stringify(values));

//ES6 style
console.log('ES6 style');
var keys = words.map(word => {
  return word;
});
console.log('Keys :: ' + JSON.stringify(keys));//same as "words"

var values = words.map(word => {
  return words.filter(w => {
    return word != w; //all words except w
  });
});
console.log('Values :: ' + JSON.stringify(values));

//or even All In One
console.log('All In One');
var keyValues = words.map(word => {
return [word, words.filter(w => {return word != w;})];
});
console.log(JSON.stringify(keyValues));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是一个构建输出的简单循环。

外部循环用于您的键,内部循环构建一个集合,该集合被推送到您的值数组

var BaseWord = 'dog';
var Synonyms = ['canine','mutt','hound'];
var Keys = Synonyms;
var Values = [];

Keys.unshift( BaseWord ); // add baseword to the start of Keys

for( var i = 0; i < Keys.length; i++ )
{
  var Set = [];
  for( var j = 0; j < Keys.length; j++ )
  {
    if( Keys[j] !== Keys[i] )
    {
      Set.push( Keys[j] );
    }
  }
  Values.push( Set );
}

console.log("the new keys array is :: %s", JSON.stringify( Keys ) );
console.log("the new Values array is :: %s", JSON.stringify( Values ) );

以下是我将如何在PHP中执行此操作

$BaseWord = 'dog';
$Synonyms = array('dog','canine','mutt','hound');

$keys = array( $BaseWord ) + $Synonyms;
$values = array();

foreach( $keys as $key )
{
  $values[] = array_values( array_diff( $keys, array( $key ) ) );
}

echo json_encode( $keys );
echo json_encode( $values );

答案 2 :(得分:1)

看起来@Scuzzy有一个关于如何做的答案。我会让你知道你做错了什么。

<强> 1。此

var tempValues = words;

words是一个数组。这意味着它通过引用传递。这意味着tempValue IS words,您对tempValue所做的任何修改都将对words进行。这让我想到了下一点:

<强> 2。您正在使用拼接错误

tempValues.splice(tempValues[o]);

这转换为:

tempValues.splice("dog");

第一次通过那个循环。不幸的是,Array.splice没有将字符串作为第一个参数。它需要一个索引。 MDN不记录传递字符串时的作用。但它表现得好像你放了0。

.splice(0)表示从第0个索引开始删除数组中的所有内容。所以,在你通过临时数组的第一个循环中,它将所有东西都撕掉,然后不再循环(因为没有什么可以循环)。所以,tempArray变成了[]。

相关问题