How to get the common values in an array - javascript

For example i am having an array of data as below
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]
i need to list the same data as below in javascript
var arrDataSorted = ["40-25","50-48","30-25","40-23","40-45","40-50","40-50"]
need only the common data that replicates also the null to be removed.
What is the best solution to solve this.

You can try using Array.prototype.filter() to remove null values and Set to get the unique values. Finally use the Spread syntax (...) to transform the set result into an array.
Try the following way:
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
var arrDataSorted = [...new Set(arrData.filter(i => i))];
console.log(arrDataSorted);

You can create a set from an array which will automatically remove duplicates:
let arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
let set = new Set(arrData);
This will still keep the null, which you can remove with a delete call, and convert back to array with the spread ... operator. The final code will be:
let set = new Set(arrData);
set.delete(null);
let distinctArr = [...set];

add the values into the set if the value is not null and convert it to array.
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
var setData = new Set();
for(var data of arrData) {
if(data) {
setData.add(data);
}
}
var arrDataSorted = [...setData];
console.log(arrDataSorted);

Add this function to your code:
function removeCommonValues(arr) {
let result = [];
for(let i=0; i < arr.length-1; ++i) {
if(result.includes(arr[i]) === false && arr[i] !== null)
result.push(arr[i])
}
return result
}
Usage:
removeCommonValues(["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]) // Return ["40-25", "50-48", "30-25", "40-23", "40-45", "40-50"]

var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]
var set = new Set();
for ( var i = 0 ; i< arrData.length;i++ ) {
if(arrData[i]!==null) {
set.add(arrData[i]);
}
}
var newArr = [...set]

You could use array built-in reducer method, in the next code i'm starting with an empty array, and i'm only returning the items that are not null and are not already in the array.
const data = arrData.reduce((state, value) => {
if(value && !state.includes(value)) {
return [...state, value];
}
return state;
}, [])

var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]
const output = [];
arrData.forEach(val => {
if(output.indexOf(val) === -1 && val !== null) {
output.push(val);
}
});
console.log(output);

The function can be in a separated file to be reused between multiple pages. Then you can call that function to filter distinct values that are not null.
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
function fn(value,index,self){
return self.indexOf(value) === index && value;
}
console.log(arrData.filter(fn));

Related

JQuery remove duplicate from array where string contains same text

I have an array with X number of items. Each has variables separated by a pipe character. In a loop I can split on the pipe to get the second item; but how do I splice to remove the duplicate.
"Sometext|22621086|address|333629dc87894a7ea7df5291fa6d1836|PC_E|1803"
"Sometext2|22622138|working|d3e70175ffe942568cd21f1cf96f4d63|PC_E|1803"
"Sometext3|22622138|working|851946e6325445da99c113951590f714|PC_E|1803"
Results should be this.
"Sometext|22621086|address|333629dc87894a7ea7df5291fa6d1836|PC_E|1803"
"Sometext2|22622138|working|d3e70175ffe942568cd21f1cf96f4d63|PC_E|1803"
Note that the duplicate 22622138 is a random number so the solution needs to work for any number in this location (it's always in the arr[1] position).
This is what I tried:
$.each(arr_transcript, function (i, e) {
if (e.length != 0) {
var arr = e.split("|")
var i = arr_transcript.indexOf(arr[1]);
if (i != -1) {
arr_transcript.splice(i, 1);
}
}
});
Here's a generic function:
function uniqBy(a, key) {
let seen = new Set();
return a.filter(item => {
let k = key(item);
return !seen.has(k) && seen.add(k);
});
};
var data = [
"Sometext|22621086|address|333629dc87894a7ea7df5291fa6d1836|PC_E|1803",
"Sometext2|22622138|working|d3e70175ffe942568cd21f1cf96f4d63|PC_E|1803",
"Sometext3|22622138|working|851946e6325445da99c113951590f714|PC_E|1803"
];
var result = uniqBy(data, item => item.split('|')[1]);
console.log(result)
See here for more info.
Create a map of the numbers you want to check against, and then filter based on that
var arr_transcript = [
"Sometext|22621086|address|333629dc87894a7ea7df5291fa6d1836|PC_E|1803",
"Sometext2|22622138|working|d3e70175ffe942568cd21f1cf96f4d63|PC_E|1803",
"Sometext3|22622138|working|851946e6325445da99c113951590f714|PC_E|1803"
];
var map = arr_transcript.map(function(text) {
return text.split('|')[1];
});
var filtered = arr_transcript.filter(function(item, index) {
return index === map.lastIndexOf( map[index] );
});
console.log(filtered)

push only unique elements in an array

I have array object(x) that stores json (key,value) objects. I need to make sure that x only takes json object with unique key. Below, example 'id' is the key, so i don't want to store other json objects with 'item1' key.
x = [{"id":"item1","val":"Items"},{"id":"item1","val":"Items"},{"id":"item1","val":"Items"}]
var clickId = // could be "item1", "item2"....
var found = $.inArray(clickId, x); //
if(found >=0)
{
x.splice(found,1);
}
else{
x.push(new Item(clickId, obj)); //push json object
}
would this accomplish what you're looking for? https://jsfiddle.net/gukv9arj/3/
x = [
{"id":"item1","val":"Items"},
{"id":"item1","val":"Items"},
{"id":"item2","val":"Items"}
];
var clickId = [];
var list = JSON.parse(x);
$.each(list, function(index, value){
if(clickId.indexOf(value.id) === -1){
clickId.push(value.id);
}
});
You can't use inArray() because you are searching for an object.
I'd recommend rewriting a custom find using Array.some() as follows.
var x = [{"id":"item1","val":"Items"},{"id":"item1","val":"Items"},{"id":"item1","val":"Items"}]
var clickId = "item1";
var found = x.some(function(value) {
return value.id === clickId;
});
alert(found);
Almost 6 years later i ended up in this question, but i needed to fill a bit more complex array, with objects. So i needed to add something like this.
var values = [
{value: "value1", selected: false},
{value: "value2", selected: false}
//there cannot be another object with value = "value1" within the collection.
]
So I was looking for the value data not to be repeated (in an object's array), rather than just the value in a string's array, as required in this question. This is not the first time i think in doing something like this in some JS code.
So i did the following:
let valueIndex = {};
let values = []
//I had the source data in some other and more complex array.
for (const index in assetsArray)
{
const element = assetsArray[index];
if (!valueIndex[element.value])
{
valueIndex[element.value] = true;
values.push({
value: element.value,
selected: false
});
}
}
I just use another object as an index, so the properties in an object will never be repated. This code is quite easy to read and surely is compatible with any browser. Maybe someone comes with something better. You are welcome to share!
Hopes this helps someone else.
JS objects are great tools to use for tracking unique items. If you start with an empty object, you can incrementally add keys/values. If the object already has a key for a given item, you can set it to some known value that is use used to indicate a non-unique item.
You could then loop over the object and push the unique items to an array.
var itemsObj = {};
var itemsList = [];
x = [{"id":"item1","val":"foo"},
{"id":"item2","val":"bar"},
{"id":"item1","val":"baz"},
{"id":"item1","val":"bez"}];
for (var i = 0; i < x.length; i++) {
var item = x[i];
if (itemsObj[item.id]) {
itemsObj[item.id] = "dupe";
}
else {
itemsObj[item.id] = item;
}
}
for (var myKey in itemsObj) {
if (itemsObj[myKey] !== "dupe") {
itemsList.push(itemsObj[myKey]);
}
}
console.log(itemsList);
See a working example here: https://jsbin.com/qucuso
If you want a list of items that contain only the first instance of an id, you can do this:
var itemsObj = {};
var itemsList = [];
x = [{"id":"item1","val":"foo"},
{"id":"item2","val":"bar"},
{"id":"item1","val":"baz"},
{"id":"item1","val":"bez"}];
for (var i = 0; i < x.length; i++) {
var item = x[i];
if (!itemsObj[item.id]) {
itemsObj[item.id] = item;
itemsList.push(item);
}
}
console.log(itemsList);
This is late but I did something like the following:
let MyArray = [];
MyArray._PushAndRejectDuplicate = function(el) {
if (this.indexOf(el) == -1) this.push(el)
else return;
}
MyArray._PushAndRejectDuplicate(1); // [1]
MyArray._PushAndRejectDuplicate(2); // [1,2]
MyArray._PushAndRejectDuplicate(1); // [1,2]
This is how I would do it in pure javascript.
var x = [{"id":"item1","val":"Items"},{"id":"item1","val":"Items"},{"id":"item1","val":"Items"}];
function unique(arr, comparator) {
var uniqueArr = [];
for (var i in arr) {
var found = false;
for (var j in uniqueArr) {
if (comparator instanceof Function) {
if (comparator.call(null, arr[i], uniqueArr[j])) {
found = true;
break;
}
} else {
if (arr[i] == uniqueArr[j]) {
found = true;
break;
}
}
}
if (!found) {
uniqueArr.push(arr[i]);
}
}
return uniqueArr;
};
u = unique(x, function(a,b){ return a.id == b.id; });
console.log(u);
y = [ 1,1,2,3,4,5,5,6,1];
console.log(unique(y));
Create a very readable solution with lodash.
x = _.unionBy(x, [new Item(clickId, obj)], 'id');
let x = [{id:item1,data:value},{id:item2,data:value},{id:item3,data:value}]
let newEle = {id:newItem,data:value}
let prev = x.filter(ele=>{if(ele.id!=new.id)return ele);
newArr = [...prev,newEle]

Javascript remove duplicated object from array

i'm having trouble to remove duplicated object from my array
example:
var list = [{place:"AAA",name:"Me"}, {place:"BBB",name:"You"}, {place:"AAA",name:"Him"}];
in this example i have 3 objects, and i want to remove the object that have the duplicated place
Just in case someone wonders: underscore.js solution:
var list = [{place:"AAA",name:"Me"}, {place:"BBB",name:"You"}, {place:"AAA",name:"Him"}];
_.uniq(list, function(item, key, a) {
return item.place;
})
Example Fiddle
A simple one:
var list = [{place:"AAA",name:"Me"}, {place:"BBB",name:"You"}, {place:"AAA",name:"Him"}];
list.forEach(function(i) {
var duplicates = list.filter(function(j) {
return j !== i && j.place == i.place;
});
duplicates.forEach(function(d) { list.splice(list.indexOf(d), 1); });
});
// list = [{place:"AAA",name:"Me"}, {place:"BBB",name:"You"}];
document.write(JSON.stringify(list));
As you added:
i want to remove just one, dont matter wich one
If you want to remove duplicated items and keep only the first occcurence of particular place, you can simply use a simple loop to re-create a new array from the input:
var list = [{place:"AAA",name:"Me"}, {place:"BBB",name:"You"}, {place:"AAA",name:"Him"}];
var uniqPlace = function(array){
var result = [];
array.forEach(function(el){
if (result.filter(function(n){ return n.place === el.place }).length==0){
result.push(el);
}
})
return result;
}
Output:
uniqPlace(list);
[{"place":"AAA","name":"Me"},{"place":"BBB","name":"You"}]
Try this.
var result = {};
for (i = 0, n = arr.length; i < n; i++) {
var item = arr[i];
result[ item.place + " - " + item.name ] = item;
}
Loop the result again, and recreate the array.
i = 0;
for(var item in result) {
clearnArr[i++] = result[item];
}
Create a object to store the items by their place value, as the new item with the same key will overwrite the old one, this will easily remove all dulplicates.
var list = [{place:"AAA",name:"Me"}, {place:"BBB",name:"You"}, {place:"AAA",name:"Him"}];
var removeDuplicate = function(list) {
var keyStore = {};
var output = [];
// If you want to creata totally new one from old, use
// list = JSON.parse(JSON.stringify(list));
// The above commented out code will create a copy of list, so the items in output will not affect the original ones.
list.forEach(function(item) {
// new one overwrites old one.
keyStore[item.place] = item;
});
var key;
for (key in keyStore) {
output.push(keyStore[key]);
}
return output;
};
console.log(removeDuplicate(list));
3 way to remove duplicate objects from array
let list = [{place:"AAA",name:"Me"},
{place:"BBB",name:"You"},
{place:"AAA",name:"Him"}];
let output1 = Array.from(new Set(list.map(list=>list.place))).map(place=>{
return {
place: place,
name: list.find(a=>a.place===place).name
}
})
console.log('------------------------1st way')
console.log(output1)
let output2 = list.reduce((accumulator, element) => {
if (!accumulator.find(el => el['place'] === element['place'])) {
accumulator.push(element);
}
return accumulator;
},[]);
console.log('------------------------2nd way')
console.log(output2)
const output3 = [];
const map = new Map();
for (const object of list) {
if(!map.has(object.place)){
map.set(object.place, true);
output3.push({
place: object.place,
name: object.name
});
}
}
console.log('------------------------3rd way')
console.log(output3)

Creating an array of JSON objects from another array of JSON objects

I have a JSON array like this:
[{Company:"", FirstName:"John", SecondName:"Smith", ID:"2345"},
{Company:"SomeComp", FirstName:"", SecondName:"Kane", ID:"4363"},
{Company:"Random", FirstName:"Tom", SecondName:"", ID:"6454"}]
I want to parse this and create a new array of objects which only have non-blank attributes without IDs, i.e:
[{FirstName:"John", SecondName:"Smith"},
{Company:"SomeComp", SecondName:"Kane"},
{Company:"Random", FirstName:"Tom"}]
What is the best way of doing this in Javascript?
You can use map
The map() method creates a new array with the results of calling a
provided function on every element in this array.
var companies = [{Company:"", FirstName:"John", SecondName:"Smith", ID:"2345"},
{Company:"SomeComp", FirstName:"", SecondName:"Kane", ID:"4363"},
{Company:"Random", FirstName:"Tom", SecondName:"", ID:"6454"}];
// This returns a new array
var newArray = companies.map(function(item) {
var obj = {};
for(var prop in item) {
if (item[prop] !== "" && prop !== "id" ) {
obj[prop] = item[prop];
};
}
return obj;
});
console.log(newArray);
This should do it
var input = JSON.parse("<YOUR JSON HERE>");
var output = [];
input.forEach(function(item) {
delete item.ID;
for (var prop in item) {
if (item.hasOwnProperty(prop) && item[prop] === "") {
item[prop] = undefined;
}
}
output.push(item);
});

Nest JSON from array

I am trying to achieve something which seemed very basic but is getting me mad over the last days.
I have a simple array : ["a","b","c","d","e"] and I want to turn it into a nested JSON like this:
{"a":{"b":{"c":{"d":{"e":""}}}}}
Looping over it, I ran in problems like "how do you save the last key to set it afterwards without erasing it" and so on.
Does anyone has an idea?
You might have had problems because you were looping in the wrong direction. Try to build the object from inside-out:
array.reduceRight(function(v, key) {
var o = {};
o[key] = v;
return o;
}, "")
or, with a loop:
var val = "";
for (var i=array.length; i--; )
var o = {};
o[array[i]] = val;
val = o;
}
return val;
Here's one way to do it, recursively:
function convertToNestedObject(arr) {
var result = {};
if (arr.length === 1) {
result[arr[0]] = '';
} else {
result[arr[0]] = convertToNestedObject(arr.slice(1, arr.length));
}
return result;
}
You could pass the start index in to the function instead of using slice and creating copies of the array:
function convertToNestedObject(arr, startIndex) {
var result = {};
if (arr.length - startIndex === 1) {
result[arr[startIndex]] = '';
} else {
result[arr[startIndex]] = convertToNestedObject(arr, startIndex + 1);
}
return result;
}
Example: http://jsfiddle.net/jwcxfaeb/1/
Put current element as key and empty object ({}) as value. Continue with newly inserted empty object.
function toNested(arr){
var nested = {};
var temp = nested;
for(var i=0; i<arr.length; i++){
temp[arr[i]] = {};
temp = temp[arr[i]];
}
return nested;
}

Categories