简体   繁体   English

从数组获取值-Javascript

[英]Getting Values from array - Javascript

Trying my best, but still not able to log the result at the end. 尽我所能,但最后仍无法记录结果。

var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];

function foo(arr) {
    var a = [], b = [], prev;

    arr.sort();
    for ( var i = 0; i < arr.length; i++ ) {
        if ( arr[i] !== prev ) {
            a.push(arr[i]);
            b.push(1);
        } else {
            b[b.length-1]++;
        }
        prev = arr[i];
    }

    return [a, b];
}

var result = foo(arr);
var a = result[0]
var b = result[1]
var aa=a.split(",");
var ab=b.split(",");
var a = a.split(",").length;
var b = b.split(",").length;
for (c = 0; c < a; c++){
console.log(aa[c]);
console.log(ab[c]);}

I want to get values from two array result[0] and result[1] one by one in the loop. 我想在循环中一一从两个数组result [0]和result [1]中获取值。
Right now I am able to get all the values comma separated but when I split values, nothing shows up. 现在,我能够将所有值逗号分隔,但是当我分割值时,什么也没有显示。

You can create an empty object to track the number of repetitions & an array to hold only unique values.Use indexOf to find if element already exist in uniqArray . 你可以创建一个空的对象跟踪重复和阵列的数量仅容纳唯一values.Use indexOf找到,如果元素已经存在uniqArray

 var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9]; var repCount = {}, // to track number of repetitions uniqArray = []; // holds only unique values arr.forEach(function(item) { if (uniqArray.indexOf(item) == -1) { // id item is not present push it uniqArray.push(item) } // check if the object already have a key for example 2,4,5,9 if (!repCount.hasOwnProperty(item)) { repCount[item] = 1 // if not then create new key } else { // if it is there then increase the count repCount[item] = repCount[item] + 1 } }) console.log(uniqArray, repCount) 

Looking at your comment... 看着你的评论...

So basically i want to get the unique no. 所以基本上我想获得唯一的编号。 from array and the no. 从数组和没有。 of repetition of that particular value into another variable 该特定值重复到另一个变量中

You can achieve this by using reduce function 您可以通过使用reduce函数来实现

 var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9]; var a = arr.reduce(function (acc, next) { acc[next] = acc[next] ? acc[next] + 1 : 1; return acc; }, {}); console.log(a); 

which gives you a hash with unique numbers as keys and their counts as values. 这会为您提供一个哈希,以唯一的数字作为键,以其计数作为值。 From here you can easily break it into two arrays if you really need to.. 如果需要,您可以从此处轻松将其分为两个数组。

You were almost there: 您几乎在那里:

  var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9]; function foo(arr) { var a = [], b = [], prev; arr.sort(); for ( var i = 0; i < arr.length; i++ ) { if ( arr[i] !== prev ) { a.push(arr[i]); b.push(1); } else { b[b.length-1]++; } prev = arr[i]; } return [a, b]; } var result = foo(arr); var a = result[0] var b = result[1] for (i=0; i<a.length; i++){ console.log("Number: " + a[i] + "; Time repeated:"+ b[i]); } 

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

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