2017-10-05 132 views
0

我在這裏有一個數據集合,您可以在下面看到。 我想要的是獲得那個elementindex,它在數組中具有唯一值。查找在數組中沒有任何重複的元素索引

var setArray = [ false, true, false, false ] 
// Sample result will be 1, the index of unique value in array is true 
// and has a index of 1 
// code here to get the index... 

我該如何解決這個問題?

+0

是值只有永遠會是真的還是假的? – CBroe

+1

請添加更多用例以及您嘗試的內容。 –

+0

嘿約翰,檢查我的答案,應該是你正在尋找的。 :) –

回答

1
var setArray = [ false, true, false, false ] 

function singles(array) { 
     for(var index = 0, single = []; index < array.length; index++) { 
      if(array.indexOf(array[index], array.indexOf(array[index]) + 1) == -1) single.push(index);  
     }; 
     return single; 
    }; 

singles(setArray); //This will return 1 

一個由ThinkingStiff稍加修改功能上this問題,以滿足您的需求。只需傳入數組,它將返回唯一元素的索引值!那很簡單。讓我知道事情的後續。

+0

你做到了兄弟,謝謝。 –

+1

@ JohnReyM.Baylen樂意幫忙! –

1

您是否嘗試過以下算法: 對於數組中的每個項目,找到第一個出現的索引和下一個出現的索引。如果下一次出現的索引是-1,則它是唯一的。

var setArray = [ false, true, false, false ]; 
var unique = []; 

setArray.forEach(item => { 
    let firstIndex = setArray.indexOf(item, 0); 
    let secondIndex = setArray.indexOf(item, firstIndex + 1); 
    if(secondIndex < 0) { 
    unique.push(firstIndex); 
    } 
}); 

例如參見下面的小提琴:
https://jsfiddle.net/yt24ocbs/

0

此代碼將返回數組中所有唯一元素的索引數組。它接受不同類型的值:字符串,數字,布爾值。

"use strict"; 
 

 
let strings = ["date1", "date", false, "name", "sa", "sa", "date1", 5, "8-()"]; 
 
let result = []; 
 

 
let data = strings.reduce((acc, el) => { 
 
    acc[el] = (acc[el] || 0) + 1; 
 
    return acc; 
 
}, {}); 
 

 
let keys = Object.keys(data); 
 

 
for (let i = 0, max = keys.length; i < max; i++) { 
 
    if (data[keys[i]] === 1) { 
 
     let index = strings.indexOf(keys[i]); 
 

 
     if (index === -1) { 
 
      index = strings.indexOf(+keys[i]); 
 
     } 
 

 
     if (index === -1) { 
 
      index = strings.indexOf(keys[i] === true); 
 
     } 
 

 
     result.push(index); 
 
    } 
 
} 
 

 
result.sort((a, b) => {return a - b}); 
 

 
console.log(result);

0

您可以映射爲唯一值的索引,然後只過濾索引。

var array = [false, true, false, false], 
 
    result = array 
 
     .map(function (a, i, aa) { return aa.indexOf(a) === aa.lastIndexOf(a) ? i : -1; }) 
 
     .filter(function (a) { return ~a; }); 
 

 
console.log(result[0]);

ES6

var array = [false, true, false, false], 
 
    result = array 
 
     .map((a, i, aa) => aa.indexOf(a) === aa.lastIndexOf(a) ? i : -1) 
 
     .filter(a => ~a); 
 

 
console.log(result[0]);