Answers for "how to create unique array from duplicate values using for loop"

0

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

const arrayNonUniq = array => {
    if (!Array.isArray(array)) {
        throw new TypeError("An array must be provided!")
    }

    return array.filter((value, index) => array.indexOf(value) === index && array.lastIndexOf(value) !== index)
}

arrayNonUniq([1, 1, 2, 3, 3])
//=> [1, 3]

arrayNonUniq(["foo", "foo", "bar", "foo"])
//=> ['foo']
Posted by: Guest on August-11-2021
0

findng and replacing duplicate values in an array

int[] arr = { 123, 129, 1928, 918273645, 12345, 123, 543, 543, 123, 123 };
int size = arr.length;
		
Scanner in = new Scanner(System.in);

for (int i = 0; i < size; i++) {
	for (int j = i; j < size; j++) {
		if (i == j) {
			continue;
		}
		if (arr[i] == arr[j]) {
			System.out.println("Duplicate found of " + i + " at " + j);
			System.out.print("Input replacement: ");
			int replacement = in.nextInt();
			boolean duplicate = true;
            do {
				try {
					arr[j] = replacement;
					for (int k = 0; k < j; k++) {
						if (arr[j] == arr[k]) {
							System.out.println("You just input at " + j + " the same value as  " + k);
							throw new Exception();
						}
					}
					duplicate = false;
				} catch (Exception e) {
					System.out.println("Please enter another value: ");
					replacement = in.nextInt();
				}
			} while (duplicate);
		}
	}
}
Posted by: Guest on July-28-2020

Code answers related to "how to create unique array from duplicate values using for loop"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language