如何删除包含特定短语的特定值之间的数组项

时间:2018-09-25 15:02:50

标签: javascript arrays

我正在使用Javascript。我有一个数组,我想过滤掉包含特定短语的某些值之间的所有数组值。这是一个示例数组:

   var array = [
      '[en]: The sun rises at 6:00',
      '[en]: Its time for brakefast',
      '[en]: comment_start',
      '[en]: Lorun ipsum a dummy text',
      '[en]: Mauris consequat massa ante',
      '[en]: In hac habitasse platea dictumst',
      '[en]: comment_end',
      '[en]: The sun sets at 6:30'
    ]

按照上述示例javascript数组,如何删除包含短语“ comment_start ”和“ comment_end 数组值 >”?

目前,我没有使用任何第三方库来像Loadash一样处理数组和对象。

2 个答案:

答案 0 :(得分:4)

我们可以尝试类似的操作,一旦点击评论部分,我们将开始过滤,一旦退出,我们将停止。

您也可以类似的方式使用array.reduce。

  var array = [
	  '[en]: The sun rises at 6:00',
	  '[en]: Its time for brakefast',
	  '[en]: comment_start',
	  '[en]: Lorun ipsum a dummy text',
	  '[en]: Mauris consequat massa ante',
	  '[en]: In hac habitasse platea dictumst',
	  '[en]: comment_end',
	  '[en]: The sun sets at 6:30'
	];
  
  var inCommentSection = false;
  var result = array.filter(v => {
	if (!inCommentSection) {
		inCommentSection = v.includes("comment_start");
	} else {
		inCommentSection = !v.includes("comment_end");
		return false;
	}
	return !inCommentSection;
  });
  
  
 console.log("Result", result);

答案 1 :(得分:0)

这是使用.indexOf()和.slice()的解决方案。 根据评论进行编辑,以不使用'[en] ...'

var array = [
      '[en]: The sun rises at 6:00',
      '[en]: Its time for brakefast',
      '[en]: comment_start',
      '[en]: Lorun ipsum a dummy text',
      '[en]: Mauris consequat massa ante',
      '[en]: In hac habitasse platea dictumst',
      '[en]: comment_end',
      '[en]: The sun sets at 6:30'
    ]
const start = array.indexOf(array.find(element => {
                return element.match('comment_start')
              })
            )
const end = array.indexOf(array.find(element => {
                return element.match('comment_end')
              })
            )
const middleComments = array.slice(start + 1, end)

return middleComments