简体   繁体   English

将文本排列成数字,找到匹配的值并排序

[英]Array text to numbers, find matching values and sort

I have an array which looks like this: 我有一个看起来像这样的数组:

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

1/ I would like to turn it in to this 1 /我想把它变成这个

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

2/ I would then like to find matching values, by looking for the most number: 2 /然后,我想通过查找最多的数字来找到匹配的值:

[8]

This first has been solved with this: 首先解决了这个问题:

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/ If the are no matching values like this 3 /如果没有像这样的匹配值

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

4/ Then I need to compare this array to another array, such as this 4 /然后我需要将此数组与另一个数组进行比较,例如

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

If the first number in <4> array above appears in <3> array, then get that number, ie in the above example I need to get 6. The <4> array will be static values and not change. 如果上面的<4>数组中的第一个数字出现在<3>数组中,则获取该数字,即在上面的示例中,我需要获取6。<4>数组将是静态值,并且不会更改。 The numbers is <3> will be dynamic. 数字为<3>将是动态的。

EDIT Not the most elegant of answers, but I do have something working now. 编辑不是最优雅的答案,但是我现在确实有一些工作。 I didn't compare the original array directly with the second array, instead used simple if/else statements to do what I needed: 我没有直接将原始数组与第二个数组进行比较,而是使用简单的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'); }
}

Example Fiddle 小提琴的例子

Step 1 is fairly easy by using javascript's join and split methods respectively: 分别使用javascript的joinsplit方法,第1步相当简单:

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

For step 2, several methods can be used, the most common one using an object and using the elements themselves as properties. 对于步骤2,可以使用几种方法,最常见的一种方法是使用一个对象,并将元素本身用作属性。 Since you only need to get the most occurring value if there is a reoccurring value, it can be used in the same loop: 由于仅在出现重复值时才需要获取最多的值,因此可以在同一循环中使用它:

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

After the above, the variable maxOccurring will contain the reoccurring value (if any) and max will contain the times it occured 完成上述操作后,变量maxOccurring将包含重复发生的值(如果有),而max将包含其发生的时间

For step 4 the easiest way is to loop through the compare array and get the element that occurs in the input array: 对于步骤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];}}();  

The above uses an in place function which is called immediately to be able to use return. 上面使用了一个就地函数,该函数立即被调用以能够使用return。 You could also just use a loop and assign res when found, then break from the loop. 您也可以只使用一个循环并在找到后分配res,然后中断循环。

Last update, an alternate fiddle where the above is converted to a single function: http://jsfiddle.net/v9hhsdny/5/ 最后更新,将上面的内容转换为单个函数的替代提琴: http : //jsfiddle.net/v9hhsdny/5/

Well first of all the following code results in four matching answers since the jQuery selectors are the same. 那么以下所有代码首先会得到四个匹配的答案,因为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];

You could use the eq(index) method of jQuery to select the appropriate element. 您可以使用jQuery的eq(index)方法来选择适当的元素。 However having 4 inputs with the same name is a bad practice. 但是,具有4个具有相同名称的输入是一个不好的做法。

Well lets say that the carArray has 4 different values which all consist out of comma separated numbers. 好吧,可以说carArray有4个不同的值,它们全部由逗号分隔的数字组成。 You could then do the following: 然后,您可以执行以下操作:

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

Well then we got to find the most occurring number. 好了,我们找到了出现次数最多的数字。 JavaScript doesn't have any functions for that so we will have to find an algorithm for that. JavaScript没有任何功能,因此我们将必须找到一种算法。 I found the following algorithm on this stackoverflow page 我在这个stackoverflow页面上找到了以下算法

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);

It isn't clear to me what you're trying to do in step 3 and 4, so can't answer those at the moment. 我不清楚您要在第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;
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}); 

(This won't work in most browsers) but on a side note, when ES6 becomes widely supported, your solution could look like this: (这不适用于大多数浏览器),但请注意,当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"]

Thought you might like to see a glimpse of the future! 以为您可能希望对未来有所了解!

1. 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. 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;
  }
}

I don't understand the question 3 and 4 (what "unique order" means) so I can't answer those questions. 我不理解问题3和4(“唯一顺序”的含义),所以我无法回答这些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM