如何根据字符串中数据的出现得到结果

问题描述 投票:0回答:3

嗨,我有这个测试数据,我想得到这样的结果

na ===> not available

error ===> error

ok  ===> ok

arr1 = ['na','na','ok','ok','na']  => na 

arr2 = ['ok','ok','ok','ok','error'] => error

arr2 = ['ok','ok','ok','ok','ok'] => ok
javascript jquery
3个回答
0
投票

假设你想要一个在element中出现更多次数的array,这可能会有所帮助:

var arr = ['na','na','ok'];

console.log(getMoreOccurencesElement(arr));

arr.push('ops');
arr.push('ops');
arr.push('ops');

console.log(getMoreOccurencesElement(arr));

function getMoreOccurencesElement(arr) {
return arr
  .reduce((acc, ele) => {
    var prev = acc.find(x => x.value == ele);
    if(prev) {
      prev.counter = prev.counter + 1;
      return acc;
    }
    return acc.concat({value: ele, counter: 1})
  }, [])
  .sort((a, b) => b.counter - a.counter)[0].value;
}

0
投票

使用elseif或开关确定数组中是否存在“na”或“error”。

逻辑基于“na”或“error”的第一个实例,将数组设置为该类型。不确定逻辑是否应该找到所有实例,然后根据na / error的总数/最大数设置状态。

编辑 - 我添加了一个switch语句选项来演示该路径 - 请注意,该开关的触发器是hte indexOf()表达式的结果,而不是字符串的存在。

arr1 = ['na','na','ok','ok','na'];
arr2 = ['ok','ok','ok','ok','error'];
arr3 = ['ok','ok','ok','ok','ok'];

function checkArray(arr) {
 if ( arr.indexOf('na') !== -1 ) {
  return "na";
 } else if(arr.indexOf('error') !== -1) {
    return "error";
 } else {
   return "ok";
 }
}


 console.log("Using an elseif block")
 console.log(checkArray(arr1)); // gives 'na'
 console.log(checkArray(arr2)); // gives 'error'
 console.log(checkArray(arr3)); // gives 'ok'
 
 

 
 function checkArray2(arr) {
  switch(true) {
    case  arr.indexOf('na') !== -1:
        return "na"
        break;
    case  arr.indexOf('error') !== -1:
        return "error"
        break;
    default:
        return "ok"
  }
}

 console.log(" ")
 console.log("Using a switch statement")
 console.log(checkArray2(arr1)); // gives 'na'
 console.log(checkArray2(arr2)); // gives 'error'
 console.log(checkArray2(arr3)); // gives 'ok'

0
投票

arr1 = ['na', 'na', 'ok', 'ok', 'na'];
arr2 = ['ok', 'ok', 'ok', 'ok', 'error'];
arr3 = ['ok', 'ok', 'ok', 'ok', 'ok'];

function count(arr) {
  var na_count = arr.filter(function(a) {return a === 'na';}).length;
  var error_count = arr.filter(function(a) {return a === 'error';}).length;
  var ok_count = arr.filter(function(a) {return a === 'ok';  }).length;
  var length = arr.length
  if (length === ok_count) {
    return 'ok';
  }else if (na_count > error_count) {
    return 'na';
  }else {
    return 'error';
  }

}
console.log('using arr1', count(arr1))
console.log('using arr2', count(arr2))
console.log('using arr3', count(arr3))
© www.soinside.com 2019 - 2024. All rights reserved.