数组文本到数字,查找匹配值和排序

时间:2015-08-21 07:38:01

标签: javascript arrays sorting

我有一个看起来像这样的数组:

["1,8", "4,6,8", "8,9", "6,9"]

1 /我想把它转到这个

[1,8,4,6,8,8,9,6,9]

2 /我想通过寻找最多的数字来找到匹配的值:

[8]

这首先解决了这个问题:

var carArray  = ["1,8", "4,6,8,7,7,7,7", "8,9", "6,9"];

//1) create single array
var arr = carArray.join().split(','); 

//2) find most occurring
var counts = {}; //object to hold count for each occurence    
var max = 0, maxOccurring;
arr.forEach(function(el){     
    var cnt = (counts[el] || 0); //previous count
    counts[el] = ++cnt;
    if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
        max=cnt;
        maxOccurring = el;
    }
});


if(maxOccurring){
    //there was an element more than once, maxOccuring contains that element
    setResult('Most occuring: ' + maxOccurring + ' (' + max + ' times)');
}
else{
    //3)/4) ???
    setResult('sorting?');
}

//below is only for test display purposes
function setResult(res){
    console.log(res);
}

3 /如果没有像这样的匹配值

[1,8,4,6,5,7]

4 /然后我需要将这个数组与另一个数组进行比较,比如这个

[6,7,4,1,2,8,9,5]

如果< 4>中的第一个数字是上面的数组出现在< 3>中。数组,然后得到那个数字,即在上面的例子中我需要得到6.< 4>数组将是静态值而不是更改。数字是< 3>。将充满活力。

编辑不是最优雅的答案,但我现在有一些工作。我没有直接将原始数组与第二个数组进行比较,而是使用简单的if / else语句来完成我需要的操作:

var carArray  = ["1,5", "4", "8,2", "3,9,1,1,1"];
//1) create single array
var arr = carArray.join().split(','); 

//2) find most occurring
var counts = {}; //object to hold count for each occurence    
var max = 0, maxOccurring;
arr.forEach(function(el){     
    var cnt = (counts[el] || 0); //previous count
    counts[el] = ++cnt;
    if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
        max=cnt;
        maxOccurring = el;
    }
});
if(maxOccurring){
    //there was an element more than once, maxOccuring contains that element
    console.log('Most occuring: ' + maxOccurring + ' (' + max + ' times)');
    console.log(maxOccurring);
}
else {
    // If not occuring, match from a list
    if(jQuery.inArray("6", arr) !== -1) { console.log('6'); }
    else if(jQuery.inArray("9", arr) !== -1) { console.log('9'); }
    else if(jQuery.inArray("7", arr) !== -1) { console.log('7'); }
    else if(jQuery.inArray("5", arr) !== -1) { console.log('5'); }
    else if(jQuery.inArray("4", arr) !== -1) { console.log('4'); }
    else if(jQuery.inArray("1", arr) !== -1) { console.log('1'); }
    else { console.log('not found'); }
}

6 个答案:

答案 0 :(得分:1)

示例Fiddle

分别使用javascript的joinsplit方法,步骤1非常简单:

var arr = carArray .join().split(',');

对于第2步,可以使用多种方法,最常用的方法是使用对象并使用元素本身作为属性。因为如果有重复发生的值,您只需要获得最多值,它可以在同一个循环中使用:

var counts = {}; //object to hold count for each occurence    
var max = 0, maxOccurring;
arr.forEach(function(el){     
    var cnt = (counts[el] || 0); //previous count
    counts[el] = ++cnt;
    if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
        max=cnt;
        maxOccurring = el;
    }
});

完成上述操作后,变量maxOccurring将包含重复出现的值(如果有),max将包含其出现的次数

对于第4步,最简单的方法是遍历比较数组并获取输入数组中出现的元素:

var cmpArr = ['6','7','4','1','2','8','9','5'];
//find the first occurrence inside the cmpArr

res = function(){ for(var i= 0 ; i < cmpArr.length; i++){ if(arr.indexOf(cmpArr[i]) !== -1)return cmpArr[i];}}();  

上面使用了一个就地功能,它可以立即调用以便能够使用返回。您也可以使用循环并在找到时分配res,然后从循环中断。

上次更新,将上述内容转换为单个函数的替代小提琴:http://jsfiddle.net/v9hhsdny/5/

答案 1 :(得分:0)

首先,以下代码会产生四个匹配的答案,因为jQuery选择器是相同的。

var questionAnswer1 = $(this).find('input[name=questionText]').val();
var questionAnswer2 = $(this).find('input[name=questionText]').val();
var questionAnswer3 = $(this).find('input[name=questionText]').val();
var questionAnswer4 = $(this).find('input[name=questionText]').val();

var carArray = [questionAnswer1, questionAnswer2, questionAnswer3, questionAnswer4];

您可以使用jQuery的eq(index)方法来选择适当的元素。但是,如果有4个同名的输入是不好的做法。

嗯,让我们说carArray有4个不同的值,这些值都是用逗号分隔的数字组成的。然后,您可以执行以下操作:

var newArr = [];
carArray.forEach(function(e) {
    e.split(",").forEach(function(n) {
        newArr.push(n);
    });
});

然后我们找到了最多的数字。 JavaScript没有任何功能,所以我们必须找到一个算法。我在this stackoverflow page

上找到了以下算法
var count = function(ary, classifier) {
    return ary.reduce(function(counter, item) {
        var p = (classifier || String)(item);
        counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
        return counter;
    }, {})
}

var occurances = count(newArr);

答案 2 :(得分:0)

我不清楚你在第3步和第4步中想要做什么,所以现在无法回答这些问题。

var ary = ["1,8", "4,6,8", "8,9", "6,9"];

var splitted = ary.reduce(function(acc, item) {
        return acc.concat(item.split(','));
    }, []);

var occurences = splitted.reduce(function(acc, item) {
        if (!acc.hasOwnProperty(item)) acc[item] = 0;
        acc[item] += 1;
        return acc;
    },{}),
    biggest = Object.keys(occurences).reduce(function (acc, key) {
        if (occurences[key] > acc.occurences) {
            acc.name = key;
            acc.occurences = occurences[key];
        }
        return acc;
    },{'name':'none','occurences':0}).name;

答案 3 :(得分:0)

var vals=["1,8", "4,6,8", "8,9", "6,9"];
// 1)  turn into number array
var arrNew=[];
for(var i=0; i<vals.length; i++)   
{ 
    arrLine=vals[i].split(",");
    for (var j=0;j<arrLine.length;j++) { arrNew.push (parseInt(arrLine[j])) }
}

//result: 
alert(arrNew.join(";");

// 2) find most common
var found=[];
for(var i=0; i<arrNew.length; i++) {
    // make an array of the number of occurrances of each value
    if (found["num"+newArray[i]]) {
        found["num"+newArray[i]] ++ ;
    } else {
        found["num"+newArray[i]]=1;
    }
}

var mostCommon={count:0,val:"ROGUE"};
for (x in found) {
    if (found[x] > mostCommon.count) {
        mostCommon.count=found[x].count;
        mostCommon.val=x;
    }
}

// result : 
alert(mostCommon.val);

//3) not quite sure what you meant there

// 4) unique values:
// at this point the 'found' list contains unique vals
var arrUnique=[];
for (x in found) {
    arrUnique.push[x];
}
// result :
alert(arrUnique.join(";"))


//sort:
arrUnique.sort(function(a, b){return a-b}); 

答案 4 :(得分:0)

(这在大多数浏览器中都不起作用),但另一方面,当ES6得到广泛支持时,您的解决方案可能如下所示:

var arr1 = ["1,8", "4,6,8", "8,9", "6,9"];
var arr2 = arr1.join().split(',');
var s = Array.from(new Set(arr2)); //Array populated by unique values, ["1", "8", "4", "6", "9"]

您可能希望看到未来的一瞥!

答案 5 :(得分:0)

1

var orgArray = ['1,8', '4,6,8', '8,9', '6,9'];
var newArray = [];
for (var i in orgArray) {
  var tmpArray = orgArray[i].split(',');
  for (var j in tmpArray) {
    newArray.push(Number(tmpArray[j]));
  }
}

2

var counts = {};
var most = null;
for (var i in newArray) {
  var num = newArray[i];
  if (typeof counts[num] === 'undefined') {
    counts[num] = 1;
  } else {
    ++(counts[num]);
  }
  if (most == null || counts[num] > counts[most]) {
    most = num;
  } else if (most != null && counts[num] === counts[most]) {
    most = null;
  }
}

我不理解问题3和4(什么&#34;唯一的顺序&#34;意思)所以我无法回答这些问题。