简体   繁体   中英

Selecting specific elements from an array

I'm trying to solve a tricky problem here. Whenever there are 3 rows together (eg 3A, 3B & 3C), I want to increment the variable 'count'. My logic only works for the first row but then fails for the rest. The answer to this problem should be 3. Can someone shed some light here?

function doThis() {
    var everySeat = [1A, 1B, 1C, 2A, 2C, 3A, 3B, 3C, 151A, 151B, 151C, 152B, 152C];
    var count;

    for (i = 1; i <= everySeat.length; i++) {
        if (everySeat[i-1] = i + ‘A’ && everySeat[i] = i + ‘B’ && everySeat[i+1] = i + ‘C’) {
            count++;
        }
    }

}

doThis();

Try this. Works fine.

function doThis() {
    var everySeat = ['1A', '1B', '1C', '2A', '2C', '3A', '3B', '3C', '151A', '151B', '151C', '152B', '152C'];
    var count = 0;

    for (var i = 1; i <= everySeat.length-2; i++) {
        var prefix = parseInt(everySeat[i-1]);
        if (everySeat[i-1] == prefix + 'A' && everySeat[i] == prefix + 'B' && everySeat[i+1] == prefix + 'C') {
            count++;
        }
    }
return count;
}

Firstly you array has syntax error. SO try below code.

var everySeat = ['1A', '1B', '1C', '2A', '2C', '3A', '3B', '3C', '151A', '151B', '151C', '152B', '152C'];
    var count =0;
    for(var i =0; i < everySeat.length ; i++ ){
    if(everySeat[i] == i + 'A' && everySeat[i+1] == i + 'B' && everySeat[i+2] == i + 'C'  ){
    count++;
    }
    }
    console.log(count);

Extended solution with Array.slice() and String.match() functions:

 var everySeat = ['1A', '1B', '1C', '2A', '2C', '3A', '3B', '3C', '151A', '151B', '151C', '152B', '152C'], count = 0; for (var i=0, l=everySeat.length; i < l-2; i++) { if (String(everySeat.slice(i,i+3)).match(/\\d+A,\\d+B,\\d+C/)) { count++; i +=2; } } console.log(count); 

You can convert it in string then match required substring occurrence.

var everySeat = ['1A', '1B', '1C', '2A', '2C', '3A', '3B', '3C', '151A', '151B', '151C', '152B', '152C'];
var str = everySeat.toString();
var count1 = (str.match(/3A,3B,3C/g) || []).length;
console.log(count1);

You could take a hash table for counting rows and add one if count is three for a row.

This proposal works for unsorted data as well.

 var array = ['1A', '1B', '1C', '2A', '2C', '3A', '3B', '3C', '151A', '151B', '151C', '152B', '152C'], count = Object.create(null), result = array.reduce(function (r, s) { var key = s.match(/\\d+/)[0]; count[key] = (count[key] || 0) + 1; return r + (count[key] === 3); }, 0); console.log(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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